ArrayList: deletes elements and arraylist elements.

Source: Internet
Author: User

ArrayList: deletes elements and arraylist elements.
 

1. Use a for loop (only progressive traversal is allowed)

    public static void main(String[] args) {        List<String> list = new ArrayList<String>();        list.add("111");        list.add("222");        list.add("333");        list.add("222");        list.add("444");        for (int i = list.size() - 1; i >= 0; i--)        {            if ("222".equals((String)list.get(i)))            {                list.remove(i);                System.out.println(list.get(i));            }        }        System.out.println("=========" + list.size());        for (String str : list)        {            System.out.println(str);        }    }

Running result:

222
222
=========== 3
111
333
444

 

2. Use the iterator to delete elements:

    public static void main(String[] args) {        List<String> list = new ArrayList<String>();        list.add("111");        list.add("222");        list.add("333");        list.add("222");        list.add("444");        Iterator<String> itr = list.iterator();        while (itr.hasNext())        {            String str = itr.next();            if ("333".equals(str))            {                itr.remove();            }        }        for (String str : list)        {            System.out.println(str);        }            }

Running result:

111
222
222
444

 

 

 E remove(int index) 
Removes the element at the specified position from the list.
 boolean remove(Object o) 
Remove the specified Element (if any) that appears for the first time from the list ).

List. remove (2 );

List. remove ("222 ");

Both methods can be used independently, instead of being used only during the time period.

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.