Java Listiterator Interface

Source: Internet
Author: User
Tags concurrentmodificationexception

Causes and solutions of concurrency modification exceptions
* A: Case Presentation
* Requirements: I have a collection, ask, I want to judge there is no "world" this element, if there is, I will add a "Java ee" element, please write code implementation.

List List = new ArrayList ();
List.add ("a");
List.add ("B");
List.add ("World");
List.add ("D");
List.add ("E");

/*iterator it = List.iterator (); //EDGE traversal, Edge add element--------is an operation not allowed by the program
while (It.hasnext ()) {
String str = (string) it.next ();
if (Str.equals ("World")) {
List.add ("Java ee");//This throws Concurrentmodificationexception concurrency modification exception
}
}*/


* B:concurrentmodificationexception appears
* Iterator traversal, collection modification collection
* C: Solution
* A: Iterator iteration element, iterator modification element (Listiterator unique function Add)//listiterator unique method to solve this problem
* B: Set traversal element, set modify element

Workaround:

Listiterator lit = List.listiterator (); //If you want to add elements during traversal, you can use the Add method in Listiterator
while (Lit.hasnext ()) {
String str = (string) lit.next ();
if (Str.equals ("World")) {
Lit.add ("Java ee");
List.add ("Java ee");
}
}

Listiterator
* Boolean hasnext () whether there is a next
* Boolean hasprevious () whether there is a previous
* Object Next () returns the next element
* Object Previous (); Returns the previous element

  

Java Listiterator Interface

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.