在使用java集合的時候,都須要使用Iterator。可是java集合中還有一個迭代器ListIterator,在使用List、ArrayList、LinkedList和Vector的時候能夠使用。這兩種迭代器有什麼區別呢?下面咱們詳細分析。這裏有一點須要明確的時候,迭代器指向的位置是元素以前的位置,以下圖所示:java
這裏假設集合List由四個元素List一、List二、List3和List4組成,當使用語句Iterator it = List.Iterator()時,迭代器it指向的位置是上圖中Iterator1指向的位置,當執行語句it.next()以後,迭代器指向的位置後移到上圖Iterator2所指向的位置。測試
首先看一下Iterator和ListIterator迭代器的方法有哪些。spa
Iterator迭代器包含的方法有:code
hasNext():若是迭代器指向位置後面還有元素,則返回 true,不然返回false對象
next():返回集合中Iterator指向位置後面的元素blog
remove():刪除集合中Iterator指向位置後面的元素索引
ListIterator迭代器包含的方法有:rem
add(E e): 將指定的元素插入列表,插入位置爲迭代器當前位置以前it
hasNext():以正向遍歷列表時,若是列表迭代器後面還有元素,則返回 true,不然返回falseio
hasPrevious():若是以逆向遍歷列表,列表迭代器前面還有元素,則返回 true,不然返回false
next():返回列表中ListIterator指向位置後面的元素
nextIndex():返回列表中ListIterator所需位置後面元素的索引
previous():返回列表中ListIterator指向位置前面的元素
previousIndex():返回列表中ListIterator所需位置前面元素的索引
remove():從列表中刪除next()或previous()返回的最後一個元素(有點拗口,意思就是對迭代器使用hasNext()方法時,刪除ListIterator指向位置後面的元素;當對迭代器使用hasPrevious()方法時,刪除ListIterator指向位置前面的元素)
set(E e):從列表中將next()或previous()返回的最後一個元素返回的最後一個元素更改成指定元素e
一.相同點
都是迭代器,當須要對集合中元素進行遍歷不須要干涉其遍歷過程時,這兩種迭代器均可以使用。
二.不一樣點
1.使用範圍不一樣,Iterator能夠應用於全部的集合,Set、List和Map和這些集合的子類型。而ListIterator只能用於List及其子類型。
2.ListIterator有add方法,能夠向List中添加對象,而Iterator不能。
3.ListIterator和Iterator都有hasNext()和next()方法,能夠實現順序向後遍歷,可是ListIterator有hasPrevious()和previous()方法,能夠實現逆向(順序向前)遍歷。Iterator不能夠。
4.ListIterator能夠定位當前索引的位置,nextIndex()和previousIndex()能夠實現。Iterator沒有此功能。
5.均可實現刪除操做,可是ListIterator能夠實現對象的修改,set()方法能夠實現。Iterator僅能遍歷,不能修改。
三:Iterator和ListIterator用法示例
ListIterator用法:
1 package com.collection; 2 3 import java.util.LinkedList; 4 import java.util.List; 5 import java.util.ListIterator; 6 7 /** 8 * @author 朱偉 9 * 鏈表中ListIterator測試 10 * 11 */ 12 public class ListIteratorTest { 13 14 public static void main(String[] args) { 15 // TODO Auto-generated method stub 16 List<String> staff = new LinkedList<>(); 17 staff.add("zhuwei"); 18 staff.add("xuezhangbin"); 19 staff.add("taozhiwei"); 20 ListIterator<String> iter = staff.listIterator(); 21 String first = iter.next(); 22 23 //刪除zhuwei 24 iter.remove(); 25 26 //把zhuwei改成simei 27 //iter.set("simei"); 28 System.out.println("first:"+first); 29 30 iter.add("xiaobai"); 31 32 //遍歷List元素 33 System.out.println("遍歷List中元素,方法一:"); 34 for(String str : staff) 35 System.out.println(str+" "); 36 37 iter = staff.listIterator(); 38 System.out.println("遍歷List中元素,方法二:"); 39 while(iter.hasNext()) 40 { 41 System.out.println(iter.next()); 42 } 43 } 44 45 }