标签:
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