写作业时用到了迭代器ListIterator,主要代码如下,使用了
.next().hasNext()
.hasPrevious()
.previous()
ListIterator<Worker> it = workerList.listIterator(); int index = 0; while(it.hasNext()) { Worker w = it.next() ; if("li4".equals(w.getName())) { // it.add( new Worker("zhao6",24,3300)); index = workerList.indexOf(w); System.out.println(index); // break; } } workerList.add(index, new Worker("zhao6",24,3300)); System.out.println(workerList.toString()); // ListIterator<Worker> it1 = workerList.listIterator(); while(it.hasPrevious()) { Worker w = it.previous() ; if("zhang3".equals(w.getName())) { it.remove(); // break; } System.out.println(workerList.toString()); }
报错Exception in thread "main" java.util.ConcurrentModificationException,检查后发现,是下面这句代码的使用使程序抛出了异常
workerList.add(index, new Worker("zhao6",24,3300));
ListIterator it 和集合 workList 同时操作一个资源,语句下方还有
即ListIterator it 未完成对集合的操作,此时就会抛出异常while(it.hasPrevious())
-----------------------------------------------------------------------------------------------------
注意:使用ListIterator的
.next().hasNext()
.hasPrevious()
遍历集合时,注意可能因指针不在集合的头或尾而"错过"某些数据.previous()