今天看書,看到書上介紹ListIterator的remove(),我想了解一下,編寫了以下代碼。java
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會拋出異常 } }
查看輸出結果:code
test0 ======================orm
[[0:hello], [1:how], [2:are], [3:you], [4:are], [5:you], [6:ok], [7:fine], [8:thank], [9:you]]rem
[[0:hello], [1:how], [2:are], [3:you], [4:are]]it
test1 ======================io
[[0:hello], [1:how], [2:are], [3:you], [4:are], [5:you], [6:ok], [7:fine], [8:thank], [9:you]]form
[[5:you], [6:ok], [7:fine], [8:thank], [9:you]]class