To traverse the list collection to delete a specified element method
One of the mistakes made in the project today is to record:
Just started careless writing for like traversal This will appear the following table out of bounds problem
Should be iterate traversal removes elements from the collection
The following is reproduced:
A wrong way:
for (int i = 0, len= list.size (); i<len;++i) {if (List.get (i) ==xxx) {list.remove (i); } }
The following exception is thrown in this way:
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) at listdemo.main ( LISTDEMO.JAVA:20)
because you removed the element, but did not change the subscript of the iteration, so that when the iteration to the last time will throw an exception
for (Int i = 0 , len= list.size ();i<len; ++i) { if (List.get (i) ==xxx) { List.remove (i); --len;//reduce a --i; } }
> The code above is correct.
iterator<string> slistiterator = list.iterator (); while (Slistiterator.hasnext ()) { string e = Slistiterator.next (); if (E.equals ("3")) { slistiterator.remove (); } }
< p>
View ArrayList source code will find that many methods are implemented internally based on the iterator interface, so the second scenario is recommended
To traverse the list collection to delete a specified element method