Home > Java > javaTutorial > body text

Method to delete specific elements in java collection class arraylist loop

高洛峰
Release: 2017-01-22 16:12:06
Original
1712 people have browsed it

During project development, we may often need to dynamically delete some elements in the ArrayList.

A 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);
  
 }
  
}
Copy after login

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)
Copy after login

Because you deleted the element, but did not change the iteration subscript, so when the 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;//减少一个
 }
  
}
Copy after login

The above code is correct.

Let’s introduce another solution below:

The List interface implements the Iterator interface internally, providing developers 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();
  }
}
Copy after login

The above is also correct, and the second option is recommended.

The implementation principles of the two solutions are quite different. The second one is just encapsulated by jdk.

Looking at the ArrayList source code, you will find that many methods are internally implemented based on the iterator interface, so it is recommended to use the second solution.

The above is the entire method of deleting specific elements in the java collection class arraylist loop brought to you by the editor. I hope you will support the PHP Chinese website~

More related methods of deleting specific elements in the java collection class arraylist loop Please pay attention to the PHP Chinese website for articles!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template