Traversing the list in Java encounters the need to dynamically delete some elements in ArrayList
The wrong way
for (int i = 0, Len = list.size (), i < Len; i++) { if(List.get (i) = = 1) { list.remove (i); } }
This throws an exception
Exception in thread "main" Java.lang.indexoutofboundsexception:index:3, Size:3 at Java.util.ArrayList.RangeCheck (Unknown source) at java.util.ArrayList.get (Unknown source
This exception is due to the deletion of the element after the corresponding angle is not changed, traversing to the last time will not be found to throw this exception
Correct procedure to remove subscript and navigate to traverse location
for (int i = 0, Len = list.size (), i < Len; i++) { if(List.get (i) = = 1) { List.remove ( i); Len--; I--; } }
Or use Java's iterator interface to implement traversal
iterator<integer> Iterator = list.iterator (); while (Iterator.hasnext ()) { int i = iterator.next (); if (i = = 1) { iterator.remove (); } }
List in Java dynamic remove processing