Often we want to delete some elements in the collection. Some may write like this.
public void operate (List list) {
for (Iterator it = List.iterator (); It.hasnext ();) {
String str = (string) it.next ();
if (Str.equals ("Chengang")) {
List.remove (str);
}
}
}
This writing will report the following exception as soon as it runs:
Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.abstractlist$itr.checkforcomodification (abstractlist.java:449)
Because the list is not allowed to delete its elements when it is in the loop. Later I did, a very stupid way, the idea is that: Create a list to be deleted from the element, after the loop, using the List.removeall method to delete the element. The code is 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 really solve the problem, but the method is too cumbersome, in fact, there can be more simple and more efficient way, is to use the Iterator.remove method, as follows:
for (Iterator it = List.iterator (); It.hasnext ();) {
String str = (string) it.next ();
if (Str.equals ("Chengang")) {
It.remove ();
}
}
So, the more basic knowledge you have about Java, the more concise your code will be. Conversely, if your code is particularly complex, there must be a problem with the method or design.
How to delete elements in a Java collection