Java series: Add and remove for listiterator about LinkedList

Source: Internet
Author: User

Static void Testlistiteratoradd () {        linkedlistnew linkedlist<string>();        Strlist.add ("1");        Strlist.add ("2");        Strlist.add ("3");        Print ("init content:");        Printcollection (strlist);                Listiterator<String> it = strlist.listiterator ();        It.next ();        It.add ("1.1");        It.add ("1.2");                Print ("After insert 2 item");        Printcollection (strlist);            }

The output is as follows, the basic and expected consistent, can be continuous add, each time the add is equivalent to inserting after the cursor, the iterator can be imagined as the cursor.

init content:collection Content:    item:1    item:2    Item:32  ItemCollection content:    item: 1    Item:1.1    Item:1.2    Item: 2     Item:3

About the Listiterator.remove test

Static voidTestlistiteratorremove () {LinkedList<String> strlist =NewLinkedlist<string>(); Strlist.add ("1"); Strlist.add ("2"); Strlist.add ("3"); Print ("Init content:");                Printcollection (strlist); Listiterator<String> it =Strlist.listiterator ();        It.next (); It.remove ();//OKPrint ("After remove 1 item");                Printcollection (strlist); It.remove ();//ErrorPrint ("After remove 2 item");    Printcollection (strlist); }

The output is as follows, that is, listiterator.remove is dependent on the state of the iterator, and each time you call remove, you must first call the next or previous function.

init content:collection Content:    item:1    item:2    Item:31  ItemCollection content:    item: 2    Item:3"main"  Java.lang.IllegalStateException at    java.util.linkedlist$listitr.remove (linkedlist.java:923) At    Me.ygc.javabasic.learnJava.LearnCollection.testListIteratorRemove (learncollection.java:) At    Me.ygc.javabasic.learnJava.LearnCollection.main (Learncollection.java:15)

Java series: Add and remove for listiterator about LinkedList

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.