I'm trying to do the following in Java.
I have a class that contains an ArrayList.
At certain points in the program I want to mark a position in the ArrayList.
e.g. If I had "A" and "B" then 'mark' and then add "C" and "D"
Then, when I say, 'showFrom()" I should only get to see "C" and "D".
I tried to use an Iterator to do this, but with no succes.
I get the following
Exception in thread "main" java.util.ConcurrentModificationException
at
java.util.AbstractList$Itr.checkForComodification(AbstractList.java:444)
at java.util.AbstractList$Itr.next(AbstractList.java:417)
at IteratorTest.moveIterator(IteratorTest.java:27)
at IteratorTest.main(IteratorTest.java:41)
The code I tried is the following.
import java.util.*;
public class IteratorTest {
private ArrayList a;
private Iterator i;
public IteratorTest() {
a = new ArrayList();
i = a.iterator();
}
public String toString() {
return a.toString();
}
public void add(Object o) {
a.add(o);
}
public void showAll() {
Iterator ii = a.iterator();
while (ii.hasNext())
System.out.print(ii.next() + " ");
}
// this should reset the mark
public void moveIterator() {
while (i.hasNext()) i.next();
}
public void showFrom() {
Iterator ii = i;
while (ii.hasNext()) System.out.print(ii.next());
}
public static void main(String []args) {
IteratorTest it = new IteratorTest();
it.add("A");
it.add("B");
it.showAll();
System.out.println("");
it.moveIterator();
it.add("C");
it.add("D");
it.showFrom(); // here, I hope to see only C and D
System.out.println();
}
}
Thanks for any suggestion on how to solve this problem.
Stino.