开发者

ConcurrentModificationException with vector and clear()

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 approa开发者_如何转开发ches and am wondering what is the best, simplest way to resolve this in my case (with no explicit threads involved)?


If no threads are involved, it's likely that the example you posted is incomplete.

This ConcurrentModificationException can happen simply if you modify the collection while iterating over it.

Note that this exception does not always indicate that an object has been concurrently modified by a different thread. If a single thread issues a sequence of method invocations that violates the contract of an object, the object may throw this exception. For example, if a thread modifies a collection directly while it is iterating over the collection with a fail-fast iterator, the iterator will thow this exception.

And the docs for Vector.listIterator() explicitly state that:

Note that the list iterator returned by this implementation will throw an UnsupportedOperationException in response to its remove, set and add methods unless the list's remove(int), set(int, Object), and add(int, Object) methods are overridden.

(Well actually that the docs for AbstractList.listIterator(int); Vector doesn't redefine that.)


Let me shorten that code for you:

Vector<Integer> v = new Vector<Integer>();
v.add(1);
v.add(2);
v.add(3);
for (Integer i: v) {
    System.out.println(i);
}
v.clear();

You shouldn't use listIterator() unless you do forward and backward navigation. For simple iteration use the iterator() 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 ArrayList instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜