try {
List<String> list1 = new LinkedList<String>(Arrays.asList(new String[] { "a", "b", "c" }));
ListIterator<String> listIterator1 = list1.listIterator();
listIterator1.remove();
} catch (Exception e) {
System.out.println("直接remove会报 IllegalStateException");
}
//标准的做法:在next之后才能remove
List<String> list2 = new LinkedList<String>(Arrays.asList(new String[] { "b", "a", "b", "c", "b", }));
ListIterator<String> listIterator2 = list2.listIterator();
while (listIterator2.hasNext()) {
if (listIterator2.next().equals("b")) listIterator2.remove();
}
System.out.println(list2);//[a, c]
//remove之前不能有add()
try {
List<String> list4 = new LinkedList<String>(Arrays.asList(new String[] { "a", "b", "c" }));
ListIterator<String> listIterator4 = list4.listIterator();
while (listIterator4.hasNext()) {
if (listIterator4.next().equals("b")) {
listIterator4.add("添加");
listIterator4.remove();
}
}
} catch (Exception e) {
System.out.println("remove之前有add也会报 IllegalStateException");
}
//移除指定范围内的所有元素
List<String> list3 = new LinkedList<String>(Arrays.asList(new String[] { "a", "开始", "b", "c", "d", "结束", "e" }));
ListIterator<String> listIterator3 = list3.listIterator();
while (listIterator3.hasNext()) {
if (listIterator3.next().equals("开始")) {
listIterator3.remove();//注释掉这行代码则不移除"开始"
while (listIterator3.hasNext()) {
if (!listIterator3.next().equals("结束")) {
listIterator3.remove();//remove之后必须再调用next方法后才能再remove
} else {
listIterator3.remove();//注释掉这行代码则不移除"结束"
break;//结束while循环
}
}
}
}
System.out.println(list3);//[a, e]
//替换指定元素
List<String> list5 = new LinkedList<String>(Arrays.asList(new String[] { "a", "b", "c" }));
ListIterator<String> listIterator5 = list5.listIterator();
while (listIterator5.hasNext()) {
if (listIterator5.next().equals("b")) {
listIterator5.remove();
listIterator5.add("替换");
}
}
System.out.println(list5);//[a, 替换, c]