日期:2014-05-20  浏览次数:20683 次

关于迭代中集合的remove问题
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;

public class IteratorTest {
public static void main(String[] args) {
Collection e=new HashSet();
  e.add("bubble sort");
  e.add("quick sort");
  e.add("insert sort");
  Iterator iter=e.iterator();
  while(iter.hasNext()){
  String algorithm=(String)iter.next();
  if(algorithm.equals("quick sort")){
  e.remove(algorithm);//改为e.remove(algorithm);就行,不改就报错
  }
  System.out.println();
  }
  System.out.println(e);
}
}
请高手解惑

------解决方案--------------------
楼主“改为e.remove(algorithm);就行,不改就报错”应该是“改为iter.remove();就行,不改就报错”吧。

简单点说吧,e.remove(algorithm)调用的是HashMap的一个接口,而iter.remove()是HashMap内部类KeyIterator的一个接口。
调用e.remove(algorithm)时,会修改modCount(HashMap的实例变量)的值,但不会同步expectedModCount(KeyIterator的实例变量)与modCount的值;而调用iter.remove()时,除了会修改modCount的值外,还会同步expectedModCount与modCount的值。
而在调用iter.next()的时候会判断expectedModCount和modCount的值是否同步,如果不同步就会抛出异常。
具体过程楼主可以参考jdk源码。