ArrayList<String> collection = new ArrayList<String>();
collection.add("Apple");
collection.add("Banana");
collection.add("Cherry");
for (String element : collection)
{
if (element.equals("Banana")) {
collection.remove(element);
}
}
如果这是真的那么为什么上面的代码片段可以正常工作?它不会像我预期的那样抛出并发修改错误。
看两个例子
// ====== not safe
List<String> ccollectionNotSafeRemoving = new ArrayList<>();
ccollectionNotSafeRemoving.add("Apple");
ccollectionNotSafeRemoving.add("Banana");
ccollectionNotSafeRemoving.add("Cherry");
for (String element : ccollectionNotSafeRemoving)
{
// when removing last element will work
if (element.equals("Banana")) {
ccollectionNotSafeRemoving.remove(element);
}
// BUT: this won't work ( java.util.ConcurrentModificationException )
// if (element.equals("Apple")) {
// ccollectionNotSafeRemoving.remove(element);
// }
}
ccollectionNotSafeRemoving.forEach(System.out::println);
// ====== better
List<String> collectionSafeRemoving = new ArrayList<>();
collectionSafeRemoving.add("Apple");
collectionSafeRemoving.add("Banana");
collectionSafeRemoving.add("Cherry");
Iterator<String> iteratorToRemove = collectionSafeRemoving.iterator();
while (iteratorToRemove.hasNext()) {
var element = iteratorToRemove.next();
if (element.equals("Apple")) {
iteratorToRemove.remove();
}
}
collectionSafeRemoving.forEach(System.out::println);