Today, a netizen asked me the collection forgot not, this asked me to tangle a bit, and finally decided to write down this set of questions, so as not to commit a similar problem:
Some elements in list and set need to be removed, while the method using edge traversal and edge deletion reported the following exception:concurrentmodificationexception in order to never forget, and also provide a reference to colleagues who meet the same problem:
The code for the error appears as follows:
Package Set;import Java.util.hashset;import Java.util.iterator;import Java.util.set;public class Demo {public static void Main (string[] args) {set<object> obj = new hashset<object> () Obj.add ("a"); Obj.add ("B"); Obj.add ("C"); System.out.println ("Before removal:" + obj.tostring ());iterator<object> it = Obj.iterator (); for (int i=0; i<obj.size (); I + +) {System.out.println (i); Object name = It.next (); if ("a". Equals (name) | | "B". Equals (name) {obj.remove (name); i--;}} System.out.println ("After removal:" + obj.tostring ());}}
Using the above notation, the above concurrenmodificationexception exception is reported because the collection cannot be deleted while traversing.
The correct operation of the list is:
Package List;import java.util.*;p ublic class Demo {public static void main (string[] args) {list<object> obj = new Ar Raylist<object> (), Obj.add ("a"), Obj.add ("B"), Obj.add ("C"); System.out.println ("Before removal:" + obj.tostring ());iterator<object> it = Obj.iterator (); for (int i=0; i<obj.size (); I + +) {System.out.println (i); Object name = It.next (); if ("a". Equals (name) | | "B". Equals (name)) {it.remove (); i--;}} System.out.println ("After removal:" + obj.tostring ());}}
The correct operation for set is:
Package Set;import Java.util.hashset;import Java.util.iterator;import Java.util.set;public class Demo {public static void Main (string[] args) {set<object> obj = new hashset<object> () Obj.add ("a"); Obj.add ("B"); Obj.add ("C"); System.out.println ("Before removal:" + obj.tostring ());iterator<object> it = Obj.iterator (); for (int i=0; i<obj.size (); I + +) {System.out.println (i); Object name = It.next (); if ("a". Equals (name) | | "B". Equals (name)) {it.remove (); i--;}} System.out.println ("After removal:" + obj.tostring ());}}
A way to iterate through the elements in the list and set set in Java