Many problems that occur when JAVA collections remove their own set Elements
The purpose of a piece of code is to delete the set items that contain the "a" string in the collection:
public class TestForeach {public static void main(String[] args){//ArrayList
lists = new ArrayList
();Collection
lists = new HashSet
();lists.add("abvd");lists.add("acvd");lists.add("bvd");lists.add("d");lists.add("a");Iterator
iter = lists.iterator();while(iter.hasNext()){String s = iter.next();if( s.contains("a") ){lists.remove(s);}}System.out.println(lists);}}
<喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + 1k3s8rfwzvajuw.vcd4kpha + pgltzybzcm9 "http://www.2cto.com/uploadfile/Collfiles/20140827/20140827085807271.jpg" alt = "\">
When you do not use Iterator to traverse collection elements:
Public class TestForeach {public static void main (String [] args) {ArrayList
Lists = new ArrayList
(); Lists. add ("abvd"); lists. add ("acvd"); lists. add ("bvd"); lists. add ("d"); lists. add ("a"); for (int I = 0; I
Output result:
[Acvd, bvd, d]
The reason why acvd is not deleted is:
In memory, when the "abvd" element of I = 0 is deleted, I ++ and the position I = 0 in lists becomes "acvd", which is the next element of the previous I = 0.
Solution when deleting elements in a set:
① Do not use the collection Object. remove (int I)/remove (Object o); instead, use the remove Method of the Iterator Object.
Cause:
The remove Method in iterator:
② If only one element is deleted, you can use the forin statement to delete the element and use the break to exit the loop.
③ Use CopyOnWriteArrayList to solve such exceptions.