有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

foreach使用Collection时Java ConcurrentModificationException背后的原因。删除()

这里关于StackOverflow的大量贡献清楚地解释了为什么在迭代集合时应该使用迭代器及其remove方法来除去集合中的元素(例如123

然而,当使用Collection.remove()而不是Iterator.remove()时,究竟是什么原因导致ConcurrentModificationException被抛出?我一直在寻找详细的答案,但没有找到。就连Java™ Tutorials也简单地说:

The for-each construct hides the iterator, so you cannot call remove.

这是什么意思?这两种实现有何不同?在下面的代码中,导致异常的事件链是什么

Collection<String> names = new ArrayList<>();
names.add("Luke");
names.add("Leia");
names.add("Anakin");

for (String name : names) {
    if (name.equals("Anakin")) {
        names.remove(name);
    }
}

共 (0) 个答案