Often we want to delete certain elements from a collection. Some may write this.
Copy the code code as follows:
public void operate(List list){
for (Iterator it = list.iterator(); it.hasNext();) {
String str = (String)it.next();
if (str.equals("chengang")){
list.remove(str);
}
}
}
As soon as this writing method is run, the following exception will be reported:
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.AbstractList$Itr.checkForComodification(AbstractList.java:449)
Because the elements of the list cannot be deleted while it is in the loop. Later, I did this, a very stupid method. The idea is this: Create a List to specifically store the elements to be deleted. After the loop, use the List.removeAll method to delete the elements. The code is as follows:
Copy the code code as follows:
public void operate(List list){
List removeList= new ArrayList();
for (Iterator it = list.iterator(); it.hasNext();) {
String str = (String)it.next();
if (str.equals("chengang")){
removeList.add(str);
}
}
list.removeAll(removeList);
}
This can indeed solve the problem, but the method is too cumbersome. In fact, there can be a simpler and more efficient method, which is to use the Iterator.remove method, as follows:
Copy the code code as follows:
for (Iterator it = list.iterator(); it.hasNext();) {
String str = (String)it.next();
if (str.equals("chengang")){
it.remove();
}
}
So, the more you know the basics of Java, the simpler your code will be. On the contrary, if your code is particularly complex, there must be something wrong with the method or design.