ArrayList deleting elements

Source: Internet
Author: User

1. Use for loop (only decrements traversal)

     Public Static voidMain (string[] args) {List<String> list =NewArraylist<string>(); List.add ("111"); List.add ("222"); List.add ("333"); List.add ("222"); List.add ("444");  for(inti = 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); }    }

Operation Result:

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

2. Remove the element with an iterator:

     Public Static voidMain (string[] args) {List<String> list =NewArraylist<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); }            }

Operation Result:

111
222
222
444

ArrayList deleting elements

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.