Delete element Remove and RemoveAll in list

Source: Internet
Author: User
public class Listtest {public
    static void Main (string[] args) {
        list<integer> List = new Arraylist<integ Er> ();
        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);
            }
        }
        SYSTEM.OUT.PRINTLN (list);
    }

Output results: [1, 2, 3, 4]
The elements in the list are not all deleted, because after each remove an element, the following elements will move forward, causing the element that has just been moved is not read. So you can solve this problem by traversing backwards, the code is as follows:

for (int i = List.size ()-1; I >= 0; i--) {
            System.out.println (i);
            if (list.get (i) = = 3) {
                list.remove (i);
            }
        }

It can also be deleted by the RemoveAll method, which is collection

list<integer> item = new arraylist<integer> ();
Item.add (3);
List.removeall (item);

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.