在使用Java集合的時候,都須要使用Iterator。可是java集合中還有一個迭代器ListIterator,在使用List、ArrayList、LinkedList和Vector的時候可使用。這兩種迭代器有什麼區別呢?下面咱們詳細分析。這裏有一點須要明確的時候,迭代器指向的位置是元素以前的位置。java
首先看一下Iterator和ListIterator迭代器的方法有哪些。學習
Iterator迭代器包含的方法有:code
ListIterator迭代器包含的方法有:對象
相同點索引
不一樣點rem
使用範圍不一樣,Iterator能夠應用於全部的集合,Set、List和Map和這些集合的子類型。而ListIterator只能用於List及其子類型。string
ListIterator有add方法,能夠向List中添加對象,而Iterator不能。it
ListIterator和Iterator都有hasNext()和next()方法,能夠實現順序向後遍歷,可是ListIterator有hasPrevious()和previous()方法,能夠實現逆向(順序向前)遍歷。Iterator不能夠。io
ListIterator能夠定位當前索引的位置,nextIndex()和previousIndex()能夠實現。Iterator沒有此功能。List
均可實現刪除操做,可是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()); }
注意:必定要先進行由前向後輸出,以後才能進行由後向前的輸出。