Java ListIterator(迭代器)
阿新 • • 發佈:2019-01-12
LIstIterator是一個更加強大的Iterator的子型別,它只能用於各種List類的訪問,儘管Iterator只能向前移動,但是ListIterator可以雙向移動,它還可以產生相對於迭代器在列表指向的當前位置的前一個和後一個元素的索引,並且可以使用set()方法替換它訪問過的最後一個元素. 你可以通過ListIterator()方法產生一個指向List開始處的ListIteraor,並且還可以通過呼叫ListIterator(n)方法建立一個一開始就指向索引列表n的元素處的ListIterator
package java.util; public interfaceListIterator<E> extends Iterator<E> { boolean hasNext(); //檢查是否有下一個元素 E next(); //返回下一個元素 boolean hasPrevious(); //check是否有previous(前一個)element(元素) E previous(); //返回previous element int nextIndex(); //返回下一element的Index int previousIndex(); //返回當前元素的Index void remove(); //移除一個elment void set(E e); //set()方法替換訪問過的最後一個元素 注意用set設定的是List列表的原始值 void add(E e); //新增一個element }
,下面示例演示了這些能力:
//: holding/ListIteration.java package object; import typeinfo.pets.*; import java.util.*; public class ListIteration {public static void main(String[] args) { List<Pet> pets = Pets.arrayList(8); ListIterator<Pet> it = pets.listIterator(); while(it.hasNext()) System.out.print(it.next() + ", " + it.nextIndex() + ", " + it.previousIndex() + "; "); System.out.println(); // Backwards: while(it.hasPrevious()) System.out.print(it.previous().id() + " "); System.out.println(); System.out.println(pets); it = pets.listIterator(3); while(it.hasNext()) { it.next(); it.set(Pets.randomPet()); } System.out.println(pets); } } /* Output: Rat, 1, 0; Manx, 2, 1; Cymric, 3, 2; Mutt, 4, 3; Pug, 5, 4; Cymric, 6, 5; Pug, 7, 6; Manx, 8, 7; 7 6 5 4 3 2 1 0 [Rat, Manx, Cymric, Mutt, Pug, Cymric, Pug, Manx] [Rat, Manx, Cymric, Cymric, Rat, EgyptianMau, Hamster, EgyptianMau] *///:~
如果想直接反序輸出可以這樣
package object; import java.util.*; public class ListInteger{ static void reverse(List<Integer> list) { ListIterator<Integer> fwd = list.listIterator(); ListIterator<Integer> rev = list.listIterator(list.size()); //這裡將rev指向了List的最後一個元素 int mid = list.size() >> 1; for(int i = 0; i < mid; i++) { Integer tmp = fwd.next(); fwd.set(rev.previous()); rev.set(tmp); } } public static void main(String[] args) { List<Integer> src = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9, 10); List<Integer> dest = new LinkedList<Integer>(src); System.out.println("source: " + src); System.out.println("destination: " + dest); reverse(dest); System.out.println("source: " + src); System.out.println("destination: " + dest); } }/* output: source: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] destination: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] source: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] destination: [10, 9, 8, 7, 6, 5, 4, 3, 2, 1] */