我知道failfast迭代器会尽力检查ConcurrentModificationException。为什么hasext或hasPrevious等方法不检查ConcurrentModificationException并抛出它???
下面的代码运行良好,因为尽管这些方法在结构上进行了修改,但并未针对 CME 检查这些方法
public static void main(String[] args) {
// TODO Auto-generated method stub
List<String> lilong = new ArrayList<String>();
lilong.add("Queen");
for(Iterator<String> iter =lilong.iterator();iter.hasNext();)
{
System.out.println(iter.next());
lilong.add("King");
lilong.remove(0);
lilong.add("Star");
lilong.remove(0);
lilong.add("Sun");
lilong.remove(0);
lilong.add("Polar Bear");
lilong.clear();
lilong.add("There you go");
}
System.out.println("size="+ lilong.size()+"##element##"+lilong.iterator().next());
}
最佳答案
hasNext
ArrayList 的迭代器不检查修改,它只查看大小。
如果您在列表中再添加一个元素,您将进入第二次迭代,然后 next
将按预期失败。
至于为什么要这样实现......对你的问题+1。
关于java - 为什么 Iterator 或 listIterator 的 hasext、hasprevious 等方法不检查 ConcurrentModificationException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21450191/