Original URL: http://javag.iteye.com/blog/403097
Method One
Java code
- arraylist<string> list = new arraylist<string> ();
- List.add ("one");
- List.add ("both");
- List.add ("both");
- List.add ("both");
- List.add ("both");
- For (int i=0;i<list.size (); i++) {
- if (List.get (i). Equals ("II")) {
- List.remove (i);
- }
- }
- SYSTEM.OUT.PRINTLN (list);
Results:
Java code
- [One, the other, the other]
Method Two
Java code
- arraylist<string> list = new arraylist<string> ();
- List.add ("one");
- List.add ("both");
- List.add ("both");
- List.add ("both");
- List.add ("both");
- for (String s:list) {
- if (S.equals ("both")) {
- List.remove (s);
- }
- }
- SYSTEM.OUT.PRINTLN (list);
Results:
Java code
- 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 Test.main (Test.java:)
Method Three:
Java code
- arraylist<string> list = new arraylist<string> ();
- List.add ("one");
- List.add ("both");
- List.add ("both");
- List.add ("both");
- List.add ("both");
- Iterator<string> iter = List.iterator ();
- while (Iter.hasnext ()) {
- String s = iter.next ();
- if (S.equals ("both")) {
- Iter.remove ();
- }
- }
- SYSTEM.OUT.PRINTLN (list);
Results:
Java code
- [One]
Conclusion:
It's better to remove or use iterators, and the rest will be problematic.
"Go" ArrayList the same time to delete----good