Remove traps in Java set iterator iterator _java

Source: Internet
Author: User

Package testlist;

Import java.util.ArrayList;
Import Java.util.Iterator;
Import java.util.List;
Import Java.util.TreeSet;

public class Testiterator {

/**
* @param args
*/
public static void Main (string[] args) {
TODO auto-generated Method Stub
list<string> list = new arraylist<string> ();
List.add ("AAA");
List.add ("BBB");
List.add ("CCC");
Iterator T = list.iterator ();
while (T.hasnext ()) {
if (T.next (). Equals ("BBB")) {///when traversing the list collection using iterator, if you want to delete any of the set elements, you must remove them when you are traversing the penultimate element exactly.
List.remove ("CCC");
}
}

treeset<string> set = new treeset<string> ();
Set.add ("ddd");
Set.add ("Eee");
Set.add ("fff");
iterator T1 = Set.iterator ();
while (T1.hasnext ()) {
if (T1.next (). Equals ("fff")) {//////If you want to delete any of the set elements, you must delete them when you are traversing the last first element, if you are using iterator to traverse the set collection.
Set.remove ("Eee");
}
}
}

}

Because there is a certain difference in the implementation of the iterator, List,set has a different representation of the List,set to delete the set elements while iterating.

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.