I have a very simple snippet of code that populates a vector, iterates through it, and then clears it. Here is basically what I’m trying in principle:
vector v = new Vector();
v.add(1);
v.add(2);
v.add(3);
ListIterator iter = v.listIterator();
while (iter.hasNext()) {
System.out.println(iter.next());
}
v.clear()
But I get a ConcurrentModificationException.
From reading up on this, apparently using “synchronized” in some fashion is the solution. But I’m seeing a couple different approaches and am wondering what is the best, simplest way to resolve this in my case (with no explicit threads involved)?
Let me shorten that code for you:
You shouldn’t use
listIterator()unless you do forward and backward navigation. For simple iteration use theiterator()method, preferably in the for-each style I show above (where the actual iterator object is hidden from you).And don’t use Vector!!! Use
ArrayListinstead.