public static void main(String[] args) {
List<String> a = new ArrayList<String>();
a.add("1");
a.add("2");
a.add("23");
for (String temp : a) {
if ("23".equals(temp)) {
a.remove(temp);
}
}
System.out.println(a);
}
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:901)
at java.util.ArrayList$Itr.next(ArrayList.java:851)
at wan.ForEach.main(ForEach.java:22)
foreach
是通过迭代器来实现的,使用迭代器遍历元素时,容器不能试图改变容器的结构,如remove、add操作会抛出异常; 可以使用迭代器的remove
Method to delete elements.The person above made it very clear. Here I will tell you two simple solutions
1. Iterator deletion
2. Copy the list to traverse, and then operate the original list.
Of course iterator deletion is recommended
What is said upstairs is very official. To put it bluntly, the method of for(Object obj:list) cannot call the remove method of list to delete elements, otherwise an exception will be thrown because the Iterator needs to be determined. structure, so there are two ways to delete it. One is to copy a list and remove the elements in the old list by looping through the new list, and the other is to use for(int i; i<count; i++) Loop, so you can delete it through the cursor. Just be careful not to cross the bounds of the array subscript.
When you are counting eggs, if someone secretly puts eggs in your basket or takes away eggs, it will cause you to count incorrectly. Unless you take away or take in the eggs yourself, you can remember the same principle. This is also true in the program.