Closed Thread Icon

Topic awaiting preservation: Anyone a Java guru here? (Page 1 of 1) Pages that link to <a href="https://ozoneasylum.com/backlink?for=7170" title="Pages that link to Topic awaiting preservation: Anyone a Java guru here? (Page 1 of 1)" rel="nofollow" >Topic awaiting preservation: Anyone a Java guru here? <span class="small">(Page 1 of 1)</span>\

 
viol
Maniac (V) Inmate

From: Charles River
Insane since: May 2002

posted posted 11-08-2003 01:18

Can anyone tell me what I am doing wrong in this sample (removing an element from a collection, during an iteration):

code:
import java.util.*;

public class IteratorDemo implements java.util.Iterator {
private Vector v = new Vector();
public IteratorDemo() {
v.addElement("10"); v.addElement("Jack"); v.addElement("Queen");
v.addElement("King"); v.addElement("Ace");
}
private int current = 0;

public String toString() {
String s = "";
for (int i = 0; i < v.size(); i++)
s = s + v.elementAt(i) + " ";
return s;
}
public boolean hasNext() {
if (current == v.size())
return false;
else
return true;
}
public Object next() {
return (Object)v.elementAt(current++);
}
public void remove() {
System.out.print("Removing " + v.remove(1) );
System.out.println(" ==> Note that \"QUEEN\" should follow but you'll see \"KING\"");
}
public static void main(String[] args) {
IteratorDemo i = new IteratorDemo();
System.out.println("The original collection is: ");
System.out.println(i);
System.out.println("Now, iterating through the collection...");
while (i.hasNext()) {
String card = (String)i.next();
System.out.println(card);
if (card == "Jack")
i.remove();
}
System.out.println("Collection after removing Jack ==> removed properly");
System.out.println(i);
System.out.println("Why the iterator skipped the Queen?");
}
}



Rooster
Bipolar (III) Inmate

From: the uterus
Insane since: Nov 2002

posted posted 11-08-2003 01:57

You need to decrement the 'current' member within the remove function. It's not a Java problem, it's just logistics. When you call v.remove() all the indices from the specified remove index are naturaly decremented by one, thus your reference index 'current' should do the same.

[Cell 1303]

viol
Maniac (V) Inmate

From: Charles River
Insane since: May 2002

posted posted 11-08-2003 02:18

Worked fine.
Thanks a lot.
You are a Java guru indeed.

« BackwardsOnwards »

Show Forum Drop Down Menu