In project development, we may often need to dynamically delete some elements in the ArrayList.
One of the wrong ways:
<pre name= "code" class= "Java" >for (int i = 0, len= list.size (); i<len;++i) {
if (list.get (i) ==xxx) {
List.remove (i);
}
}
The above method throws the following 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)
Because you deleted the element, but did not change the subscript of the iteration, so that when the iteration to the last one throws an exception.
The following improvements can be made to the above program:
for (int i = 0, len= list.size (); i<len;++i) {
if (list.get (i) ==xxx) {
list.remove (i);
--len;//reduce One
}
}
The code above is correct.
Here's a scenario we'll introduce:
The iterator interface is implemented inside the list interface, providing a developer with a iterator () to get a iterator object of the current list object.
iterator<string> slistiterator = List.iterator ();
while (Slistiterator.hasnext ()) {
String e = Slistiterator.next ();
if (E.equals ("3")) {
slistiterator.remove ();
}
}
This is also true, and it is recommended that the second option be used.
Both schemes are much worse, and the second is just the JDK encapsulation.
View ArrayList source code will find that many methods are based on the iterator interface implementation, so recommend the use of the second scenario.
The above is a small set for everyone to bring Java Collection class ArrayList cycle to delete a specific element of the method of all content, I hope that we support cloud Habitat Community ~