It was originally thought to be solved with a simple for loop, but ignoring the removal would change the size of the collection and some errors or incorrect data;
The correct way: iterator iterator; Below is a small example of the Web, and finally posted their own wrong code to help memory.
Import java.util.ArrayList;
Import Java.util.Iterator;
public class Testlist {public static void main (string[] args) {test1 ();
Test2 ();
Test3 ();
public static void Test1 () {arraylist<string> list = new arraylist<string> ();
List.add ("one");
List.add ("two");
List.add ("two");
List.add ("two");
List.add ("two");
for (int i = 0; i < list.size (); i++) {if (List.get (i). Equals ("two")) {list.remove (i);
} System.out.println ("Test1:" + list);
public static void Test2 () {arraylist<string> list = new arraylist<string> ();
List.add ("one");
List.add ("two");
List.add ("two");
List.add ("two");
List.add ("two");
for (String s:list) {if (S.equals ("two")) {List.remove (s);
} System.out.println ("Test2:" + list);
public static void Test3 () {arraylist<string> list = new arraylist<string> ();
List.add ("one");
List.add ("two");
List.add ("two");
List.add ("two"); List.add ("Two");
Iterator<string> iter = List.iterator ();
while (Iter.hasnext ()) {String s = iter.next ();
if (S.equals ("two")) {iter.remove ();
} System.out.println ("Test3:" + list);
}
}
The first method outputs
Test1: [One, two, two]
The second method is an error
Exception in thread "main" Java.util.ConcurrentModificationException
At Java.util.abstractlist$itr.checkforcomodification (abstractlist.java:372)
At Java.util.abstractlist$itr.next (abstractlist.java:343)
At Testlist.test2 (testlist.java:34)
At Testlist.main (Testlist.java:8)
The third method outputs
TEST3: [One]
The third kind of result is correct;
Note: Self Error example
Check all the plate rules below the merchant if (wmplates!= null && wmplates.size () > 0) {//for loop this is wrong; bad for the collection; Error data or directly throw an exception for (int i = 0; i < wmplates.size (); i++)
{Wmtablebookruleexample example = new Wmtablebookruleexample (); Example.createcriteria (). Andstoreidequalto (Integer.parseint (StoreId)). Andplateidequalto (Wmplates.get (i). GetId (
)). Andstatusequalto (0). Andisdeleteequalto (0);
list<wmtablebookrule> tablerulelist = tablebookruleservice.selectbyexample (example);
if (tablerulelist!= null && tablerulelist.size () > 0) {} else {wmplates.remove (i);
} iterator<wmplate> it = Wmplates.iterator ();
while (It.hasnext ()) {Wmplate plate = it.next ();
wmtablebookruleexample example = new Wmtablebookruleexample (); Example.createcriteria (). Andstoreidequalto (Integer.parseint (StoreId)). Andplateidequalto (Plate.getid ()).
Andstatusequalto (0). Andisdeleteequalto (0); list<wmtablebookrule> tablerulelist = TABLEBOOKRULESERVICE.SELECTBYexample (example);
if (null = = Tablerulelist | | tablerulelist.size () = = 0) {it.remove (); }
}
}