Java Collection class ArrayList delete specific elements in a loop

Source: Internet
Author: User

in project development, we may often need to dynamically delete some elements in the ArrayList.
A wrong way:

[Java]View PlainCopy
    1. for (int i = 0, len= list.size (); i<len;++i) {
    2. if (List.get (i) ==xxx) {
    3. List.remove (i);
    4. }
    5. }


The following exception is thrown in this way:

[Java]View PlainCopy
    1. Exception in thread "main" Java.lang.IndexOutOfBoundsException:Index: 3, Size: 3
    2. At Java.util.ArrayList.RangeCheck (Unknown Source)
    3. At Java.util.ArrayList.get (Unknown Source)
    4. At Listdemo.main (Listdemo.java:)


Because you removed the element, but did not change the subscript of the iteration, so that when the iteration to the last one will throw an exception.

The following improvements can be made to the above program:

[Java]View PlainCopy
    1. for (int i = 0, len= list.size (); i<len;++i) {
    2. if (List.get (i) ==xxx) {
    3. List.remove (i);
    4. --len; //Reduce a
    5. I.;  //Thank you for Deny_guoshou, if you do not add a comment on the 1 floor of the situation.
    6. }
    7. }

The code above is correct.

Let's introduce another scenario:

The iterator interface is implemented inside the list interface, providing a developer with a iterator () to get a iterator object for the current list object.

[Java]View PlainCopy
    1. iterator<string> slistiterator = List.iterator ();
    2. while (Slistiterator.hasnext ()) {
    3. String e = Slistiterator.next ();
    4. if (E.equals ("3")) {
    5. Slistiterator.remove ();
    6. }
    7. }

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

Both implementations are poorly implemented, and the second is just the JDK package.

View ArrayList source code you will find that many methods are implemented internally based on the iterator interface, so the second scenario is recommended.

Java Collection Class ArrayList delete specific elements in a loop

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.