今天看书,看到书上介绍ListIterator的remove(),我想了解一下,编写了如下代码。
package com.sunhang; import java.util.*; public class Main { private static <T> void print(T t){ System.out.println(t); } private List<String> generateList(){ List<String> list = new LinkedList<String>(); String[] arr = "hello how are you are you ok fine thank you".split(" "); for (int i = 0; i < arr.length; i ++){ list.add(String.format("[%d:%s]", i, arr[i])); } return list; } private void test0(){ print("test0 ======================"); List<String> list = generateList(); print(list); ListIterator<String> it = list.listIterator(5); while(it.hasNext()){ it.next(); it.remove(); } print(list); } private void test1(){ print("test1 ======================"); List<String> list = generateList(); print(list); ListIterator<String> it = list.listIterator(5); while(it.hasPrevious()){ it.previous(); it.remove(); } print(list); } private void test2(){ List<String> list = generateList(); print(list); ListIterator<String> it = list.listIterator(5); it.remove(); // 此处会抛出异常 print(list); } public static void main(String[] args){ Main main = new Main(); main.test0(); main.test1(); // main.test2(); // test2会抛出异常 } }
查看输出结果:
test0 ======================
[[0:hello], [1:how], [2:are], [3:you], [4:are], [5:you], [6:ok], [7:fine], [8:thank], [9:you]]
[[0:hello], [1:how], [2:are], [3:you], [4:are]]
test1 ======================
[[0:hello], [1:how], [2:are], [3:you], [4:are], [5:you], [6:ok], [7:fine], [8:thank], [9:you]]
[[5:you], [6:ok], [7:fine], [8:thank], [9:you]]
原文:http://my.oschina.net/u/2291753/blog/474632