Iterator和ListIterator迭代器

在使用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);
    }
}
相關文章
相關標籤/搜索