zoukankan      html  css  js  c++  java
  • Java系列: 关于LinkedList的 ListIterator的add和remove

    static void testListIteratorAdd(){
            LinkedList<String> strList = new 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);        
        }

    输出如下,基本和预期一致,可以连续add,每次add的时候就相当于在光标后面插入,此时可以把迭代器想象为光标。

    image

    init content:
    collection content:
        item:1
        item:2
        item:3
    after insert 2 item
    collection content:
        item:1
        item:1.1
        item:1.2
        item:2
        item:3

    关于ListIterator.remove的测试

    static void testListIteratorRemove(){
            LinkedList<String> strList = new LinkedList<String>();
            strList.add("1");
            strList.add("2");
            strList.add("3");
            print("init content:");
            printCollection(strList);
            
            ListIterator<String> it = strList.listIterator();
            it.next();
            it.remove();//ok        
            
            print("after remove 1 item");
            printCollection(strList);
            
            it.remove();//error
            print("after remove 2 item");
            printCollection(strList);
        }

    输出如下,也就是说,ListIterator.remove是依赖于迭代器的状态的,每次调用remove之前,必须先调用一次next或者previous函数。

    init content:
    collection content:
        item:1
        item:2
        item:3
    after remove 1 item
    collection content:
        item:2
        item:3
    Exception in thread "main" java.lang.IllegalStateException
        at java.util.LinkedList$ListItr.remove(LinkedList.java:923)
        at me.ygc.javabasic.learnJava.LearnCollection.testListIteratorRemove(LearnCollection.java:33)
        at me.ygc.javabasic.learnJava.LearnCollection.main(LearnCollection.java:15)
  • 相关阅读:
    Zookeeper 系列(五)Curator API
    Zookeeper 系列(四)ZKClient API
    Zookeeper 系列(三)Zookeeper API
    Zookeeper 系列(二)安装配制
    [bzoj 2393] Cirno的完美算数教室 (容斥原理+dfs剪枝)
    [Sdoi2013] [bzoj 3198] spring (hash+容斥原理)
    [bzoj 1471] 不相交路径 (容斥原理)
    [bzoj 3701] Olympic Games (莫比乌斯反演)
    [bzoj 2693] jzptab & [bzoj 2154] Crash的数字表格 (莫比乌斯反演)
    [51Nod 1244]
  • 原文地址:https://www.cnblogs.com/strinkbug/p/5053044.html
Copyright © 2011-2022 走看看