The Remove () method of the Java.util.List

Source: Internet
Author: User

public static void Main (string[] args) {    list<integer> List = new arraylist<integer> ();    List.add (1);    List.add (2);    List.add (3);    List.add (3);    List.add (4);    for (int i=0; i<list.size (); i++) {        if (list.get (i) = = 3) {            list.remove (i);//This is not correct, it needs to be written list.remove (i--)         }    }    System.out.println (list);}

 

if you want to traverse the list for filtering, such as filtering out a value of 3

I thought this code is simple, but still fell out of the hole, the above code to write, the element 3 is not filtered, as long as the list has adjacent 2 the same filter is not finished

after the list calls the Remove (index) method,
Removes the element at the index position, all the elements after the index are shifted left, that is, the index, in turn, 1

to ensure that all data can be manipulated, the index-1
Otherwise, an element with the original index of index+1 cannot be traversed to
(because the original index is index+1, after the remove operation, the index becomes index, and if there is no index-1 operation, it will not traverse to the element, but instead traverse the element's next element).

The Remove () method of the Java.util.List

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.