好程序员分享Java面试题:ListIterator和Iterator的异同,不少在Java面试的时候,可能都会被问到:ListIterator和Iterator,二者有什么异同。你们都知道,在使用Java集合的时候,须要使用Iterator。可是java集合中还有一个迭代器ListIterator。在使用List、ArrayList、LinkedList和Vector的时候可使用。这两个迭代器有什么异同呢?下面咱们详细分析:java
一、Iterator和ListIterator迭代器包含的方法有哪些?程序员
Iterator迭代器包含的方法有:面试
·hasNext():若是迭代器指向位置后面还有元素,则返回 true,不然返回false对象
·next():返回集合中Iterator指向位置后面的元素索引
·remove():删除集合中Iterator指向位置后面的元素rem
ListIterator迭代器包含的方法有:string
·add(E e): 将指定的元素插入列表,插入位置为迭代器当前位置以前it
·hasNext():以正向遍历列表时,若是列表迭代器后面还有元素,则返回 true,不然返回falseio
·hasPrevious():若是以逆向遍历列表,列表迭代器前面还有元素,则返回 true,不然返回falseList
·next():返回列表中ListIterator指向位置后面的元素
·nextIndex():返回列表中ListIterator所需位置后面元素的索引
·previous():返回列表中ListIterator指向位置前面的元素
·previousIndex():返回列表中ListIterator所需位置前面元素的索引
·remove():从列表中删除next()或previous()返回的最后一个元素(有点拗口,意思就是对迭代器使用hasNext()方法时,删除ListIterator指向位置后面的元素;当对迭代器使用hasPrevious()方法时,删除ListIterator指向位置前面的元素)
·set(E e):从列表中将next()或previous()返回的最后一个元素返回的最后一个元素更改成指定元素e
二、Iterator和ListIterator迭代器的相同点有哪些?
·都是迭代器,当须要对集合中元素进行遍历不须要干涉其遍历过程时,这两种迭代器均可以使用。
三、Iterator和ListIterator迭代器不一样点有哪些?
l使用范围不一样,Iterator能够应用于全部的集合,Set、List和Map和这些集合的子类型。而ListIterator只能用于List及其子类型。
lListIterator有add方法,能够向List中添加对象,而Iterator不能。
lListIterator和Iterator都有hasNext()和next()方法,能够实现顺序向后遍历,可是ListIterator有hasPrevious()和previous()方法,能够实现逆向(顺序向前)遍历。Iterator不能够。
lListIterator能够定位当前索引的位置,nextIndex()和previousIndex()能够实现。Iterator没有此功能。
l均可实现删除操做,可是ListIterator能够实现对象的修改,set()方法能够实现。Iterator仅能遍历,不能修改。
ArrayList<String> stringArrayList1 = new ArrayList<String>();
ArrayList<String> stringArrayList2 = new ArrayList<String>();
stringArrayList1.add("ok");
stringArrayList1.add("hello");
stringArrayList1.add("world");
stringArrayList2.add("好的");
stringArrayList2.add("你好");
stringArrayList2.add("世界");
stringArrayList1.addAll(stringArrayList2);
ListIterator<String> iterator = stringArrayList1.listIterator();
System.out.println("从前日后输出:");
while (iterator.hasNext()){
System.out.println("next="+iterator.next());
}
System.out.println("\r\n从后往前输出:");
while (iterator.hasPrevious()){
System.out.println("previous="+iterator.previous());
}
注意:必定要先进行由前向后输出,以后才能进行由后向前的输出。