Many problems occur when the JAVA Collection removes its 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<String> lists = new ArrayList<String>();Collection<String> lists = new HashSet<String>();lists.add("abvd");lists.add("acvd");lists.add("bvd");lists.add("d");<pre name="code" class="java"> lists.add("dfd");
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 );}}
Running result:
Cause analysis:
When you do not use Iterator to traverse collection elements:
public class TestForeach {public static void main(String[] args){ArrayList<String> lists = new ArrayList<String>();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 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. <E>
How does java Delete objects containing elements in a collection?
Remove Method
Each set has this method.
If you only know one attribute of a set member, you can only use iteration.
Iterate each element in the set, and then compare the elements with their attributes. If they match, use the remove () method.
Remove Method in java Collection
E remove (int index)
Removes an element from the specified position in the list.
Boolean remove (Object o)
Removes the specified element that appears for the first time in the list (if any ).
Note that remove is to remove the first element, so the length is 1