Tips for using the Remove () method of Java.util.List

Source: Internet
Author: User

I. list.remove (i)
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 written, it needs to be written in List.remove (i -)}} System.out.println (list);}

Similarly,when a map is traversed by keyset () or EntrySet (), it cannot delete the element inside, otherwise it will be reported java.util.ConcurrentModificationException

To avoid this, you need to iterate through the list or map and delete it by using the iterator iterator, which is removed by Iterator.remove ().

two. Recommended use of the Iterator.remove method
if (null! = List && list.size () > 0) {Iterator it = list.iterator ();         while (It.hasnext ()) {Student Stu = (Student) it.next (); if (stu.getstudentid () = = StudentID) {it.remove ();///Remove the object}}}



Java.util.List The Remove () method using the Tips

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.