Often we want to delete some elements in the collection. Some might write that.
Copy 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);
}
}
}
This type of writing will report the following anomalies:
Exception in thread "main" java.util.ConcurrentModificationException
At Java.util.abstractlist$itr.checkforcomodification (abstractlist.java:449)
Because the list cannot delete its elements while it is in the loop. Then I did it, a very stupid way, the idea is this: Create a list of the elements to be deleted specifically, after the loop, with the List.removeall method to remove the elements. The code is as follows:
Copy 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 really solve the problem, but the method is too cumbersome, in fact, there can be a simpler and more efficient way, is to use the Iterator.remove method, as follows:
Copy 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 about Java basics, the simpler the code will be. Conversely, if your code is particularly complex, there must be a problem with the method or design.