We often need to delete some elements in the set. Some may be written in this way.
Copy codeThe Code is 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 );
}
}
}
If this method is used, the following exception is reported:
Exception in thread "main" java. util. ConcurrentModificationException
At java. util. effecactlist $ Itr. checkForComodification (effecactlist. java: 449)
Because list elements cannot be deleted in a loop. Later, I did this. It was a very stupid method. The idea was like this: Create a List to store the elements to be deleted. After the loop, use List. the removeAll method deletes an element. The Code is as follows:
Copy codeThe 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 solve the problem, but the method is too cumbersome. In fact, there can be a simpler and more efficient method, that is, the Iterator. remove method is used, as shown below:
Copy codeThe Code is as follows: for (Iterator it = list. iterator (); it. hasNext ();){
String str = (String) it. next ();
If (str. equals ("chengang ")){
It. remove ();
}
}
Therefore, the more basic Java knowledge you know, the more concise the code will be written. On the contrary, if your code is particularly complex, there must be a problem with the method or design.