简体   繁体   English

在迭代Collection时删除元素

[英]removing elements while iterating the Collection

I read that the correct way of removing elements while iterating the Collection, is this way (using iterator): 我读到,在迭代Collection时删除元素的正确方法是这种方式(使用迭代器):

List<Integer> list = new ArrayList<Integer>();
list.add(12);
list.add(18);

Iterator<Integer> itr = list.iterator();

while(itr.hasNext()) {
    itr.remove();
}

But, I receive Exception in thread "main" java.lang.IllegalStateException and I don't know why. 但是,我Exception in thread "main" java.lang.IllegalStateException收到Exception in thread "main" java.lang.IllegalStateException ,我不知道为什么。 Can someone help me? 有人能帮我吗?

You never advanced to the next element by calling the next() method on the iterator. 您永远不会通过调用迭代器next()方法来前进到下一个元素。 Try: 尝试:

while(itr.hasNext()) {
    System.out.println("Removing " + itr.next());  // Call next to advance
    itr.remove();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM