集合操作出现 ConcurrentModificationException 异常


Warning: Undefined array key "HTTP_REFERER" in /www/wwwroot/prod/www.enjoyasp.net/wp-content/plugins/google-highlight/google-hilite.php on line 58

?如:
?Iterator<PowerInfo> it = list.iterator();
??? ??? while( it.hasNext() ){
?????????? PowerInfo temp = it.next();
??? ??? ??? if ( it.next.getName().equals(“teset”) ){
??? ?? ??? ??? ?list.remove(? temp );
}

这样就会抛出ConcurrentModificationException 异常。 原因:

????? Iterator 是工作在一个独立的线程中,并且拥有一个 mutex 锁。 Iterator 被创建之后会建立一个指向原来对象的单链索引表,当原来的对象数量发生变化时,这个索引表的内容不会同步改变,故当索引指针往后移动的时候就找不到要迭代的对象,按照 fail-fast 原则 Iterator 会马上抛出 java.util.ConcurrentModificationException 异常。
?????? Iterator 在工作的时候是不允许被迭代的对象被改变的。可以使用 Iterator 本身的方法 remove() 来删除对象即:

?Iterator<PowerInfo> it = list.iterator();
??? ??? while( it.hasNext() ){
?????????? PowerInfo temp = it.next();
??? ??? ??? if ( it.next.getName().equals(“teset”) ){
??? ?? ??? ??? it.remove;????? //从迭代器指向的集合中移除迭代器返回的最后一个元素,即移除当前的元素。
}