The method to remove a specific element from the java collection class arraylist loop

  • 2020-05-16 07:00:26
  • OfStack

In project development, we may need to dynamically delete 1 elements in ArrayList.

1 wrong way:


<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) 
  at ListDemo.main(ListDemo.java:20) 

Because you deleted the element, but did not change the subscript of the iteration, the exception will be thrown when the iteration reaches the last one.

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;// To reduce 1 a  
 } 
 
}

The code above is correct.

Let's introduce another one:

The List interface implements the Iterator interface internally, providing the developer with 1 iterator() to get 1 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 option 2 is recommended.

The implementation principle of both schemes is much worse, while the second one is encapsulated by jdk.

Looking at the ArrayList source code, you'll see that many of the methods are implemented internally based on the iterator interface, so the second option is recommended.


Related articles: