In project development, we may often need to dynamically delete some elements in the ArrayList.
A wrong way:
<pre name="code">for(int i = 0 , len= list.size();i<len;++i){ if(list.get(i)==XXX){ list.remove(i); } }The above method will throw 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) at ListDemo.main(ListDemo.java:20)
Because you deleted the element, but did not change the iteration subscript, so that when iteration reaches the last one, an exception will be thrown.
The above program can be improved as follows:
for(int i = 0 , len= list.size();i<len;++i){ if(list.get(i)==XXX){ list.remove(i); --len;//Reduce one} }The above code is correct.
Let's introduce another solution:
The List interface implements the Iterator interface internally, providing the developer with an iterator() to get an 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(); } }The above is also correct, and the second solution is recommended.
The implementation principles of the two solutions are much the same, and the second one is just encapsulated by jdk.
When viewing the ArrayList source code, you will find that many methods are implemented internally based on the iterator interface, so the second solution is recommended.
The above is the entire content of the method to delete specific elements in the java collection arraylist loop brought to you. I hope everyone supports Wulin.com~