A piece of code is intended to delete a collection item that contains a string of "a" in the collection:
public class Testforeach {public static void main (string[] args) {//arraylist<string> lists = new Arraylist<strin G> (); collection<string> lists = new hashset<string> () Lists.add ("ABVD"); Lists.add ("Acvd"); Lists.add ("BVD"); Lists.add ("D"); Lists.add ("a");iterator<string> iter = Lists.iterator (); while (Iter.hasnext ()) {String s = Iter.next (); if (S.contains ("a")) {Lists.remove (s);}} SYSTEM.OUT.PRINTLN (lists);}}
Cause Analysis:
When you do not use iterator to traverse a collection element:
public class Testforeach {public static void main (string[] args) {arraylist<string> lists = new arraylist<string& gt; (); Lists.add ("ABVD"); Lists.add ("Acvd"); Lists.add ("BVD"); Lists.add ("D"); Lists.add ("a"); for (int i=0; i< Lists.size (); i++) {String str = lists.get (i), if (Str.contains ("a")) {//lists.remove (i); Lists.remove (str);}} SYSTEM.OUT.PRINTLN (lists);}}
Output Result:
[Acvd, BVD, d]
The reasons why ACVD was not removed are:
In memory, when the element "ABVD" of the i=0 is removed, i++ and the i=0 position in the lists becomes the next element of the ACVD, which is i=0
Solution when deleting elements in the collection:
① do not use collection objects. Remove (int i)/remove (object o), instead use the Remove method of the Iterator object.
Reason:
Remove method in iterator:
② If you delete only one element, you can break out of the loop after you delete the element forin the statement
③ use to solve this kind of anomaly line Shuo complete copyonwritearraylist<e>
Many issues that occur when the Java collection removes its own collection elements