【问题标题】:removing elements while iterating the Collection迭代集合时删除元素
【发布时间】:2014-06-18 18:21:47
【问题描述】:

我读到在迭代集合时删除元素的正确方法是这样(使用迭代器):

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

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

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

但是,我收到了Exception in thread "main" java.lang.IllegalStateException,但我不知道为什么。 有人可以帮我吗?

【问题讨论】:

  • 阅读文档,它明确指出:IllegalStateException - if the next method has not yet been called, or the remove method has already been called after the last call to the next method

标签: java collections iterator


【解决方案1】:

你从来没有通过在迭代器上调用the next() method 来前进到下一个元素。试试:

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

【讨论】:

    猜你喜欢
    • 2012-05-13
    • 2021-05-05
    • 1970-01-01
    • 2018-07-18
    • 1970-01-01
    相关资源
    最近更新 更多