List in Java dynamic remove processing

Source: Internet
Author: User

Traversing the list in Java encounters the need to dynamically delete some elements in ArrayList

The wrong way

 for (int i = 0, Len = list.size (), i < Len; i++) {      if(List.get (i) = = 1) {         list.remove (i);      }  }  

This throws an 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

This exception is due to the deletion of the element after the corresponding angle is not changed, traversing to the last time will not be found to throw this exception

Correct procedure to remove subscript and navigate to traverse location

 for (int i = 0, Len = list.size (), i < Len; i++) {      if(List.get (i) = = 1) {         List.remove ( i);         Len--;       I--;    }  }

Or use Java's iterator interface to implement traversal

iterator<integer> Iterator = list.iterator ();    while (Iterator.hasnext ()) {      int i = iterator.next ();       if (i = = 1) {          iterator.remove ();      }  }

List in Java dynamic remove processing

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.