在使用java集合的时候,都须要使用Iterator。可是java集合中还有一个迭代器ListIterator,在使用List、ArrayList、LinkedList和Vector的时候能够使用。这两种迭代器有什么区别呢?下面咱们详细分析。这里有一点须要明确的时候,迭代器指向的位置是元素以前的位置,以下图所示:java
这里假设集合List由四个元素List一、List二、List3和List4组成,当使用语句Iterator it = List.Iterator()时,迭代器it指向的位置是上图中Iterator1指向的位置,当执行语句it.next()以后,迭代器指向的位置后移到上图Iterator2所指向的位置。code
一.相同点对象
都是迭代器,当须要对集合中元素进行遍历不须要干涉其遍历过程时,这两种迭代器均可以使用。索引
二.不一样点rem
1.使用范围不一样,Iterator能够应用于全部的集合,Set、List和Map和这些集合的子类型。而ListIterator只能用于List及其子类型。it
2.ListIterator有add方法,能够向List中添加对象,而Iterator不能。io
3.ListIterator和Iterator都有hasNext()和next()方法,能够实现顺序向后遍历,可是ListIterator有hasPrevious()和previous()方法,能够实现逆向(顺序向前)遍历。Iterator不能够。ast
4.ListIterator能够定位当前索引的位置,nextIndex()和previousIndex()能够实现。Iterator没有此功能。class
5.均可实现删除操做,可是ListIterator能够实现对象的修改,set()方法能够实现。Iterator仅能遍历,不能修改。List
ListIterator的出现,解决了使用Iterator迭代过程当中可能会发生的错误状况。
或者像上方那样break。可是不能循环全部元素
public class IteratorDemo2 { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("abc1"); list.add("abc2"); list.add("abc3"); list.add("abc4"); ListIterator<String> listit=list.listIterator(); while(listit.hasNext()){ if(listit.next().equals("b")){ /** * ListIterator有add和remove方法,能够向List中添加对象 */ listit.remove(); listit.add("itcast"); } } // Iterator<String> it=list.iterator(); // while(it.hasNext()){ // if(it.next().equals("b")){ // list.remove(0); // if(list.add("itcast")){ // break;//添加成功之后直接break;不继续判断就能够躲过异常 // } // } // } System.out.println(list); } }