Java Collection class ArrayList method for deleting a particular element in a loop _java

Source: Internet
Author: User

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 ~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.