码迷,mamicode.com
首页 > 编程语言 > 详细

Java系列: 关于LinkedList的 ListIterator的add和remove

时间:2015-12-17 10:28:40      阅读:344      评论:0      收藏:0      [点我收藏+]

标签:

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的时候就相当于在光标后面插入,此时可以把迭代器想象为光标。

技术分享

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)

Java系列: 关于LinkedList的 ListIterator的add和remove

标签:

原文地址:http://www.cnblogs.com/strinkbug/p/5053044.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!