LIstIterator是一个更加强大的Iterator的子类型,它只能用于各种List类的访问,尽管Iterator只能向前移动,但是ListIterator可以双向移动,它还可以产生相对于迭代器在列表指向的当前位置的前一个和后一个元素的索引,并且可以使用set()方法替换它访问过的最后一个元素. 你可以通过ListIterator()方法产生一个指向List开始处的ListIteraor,并且还可以通过调用ListIterator(n)方法创建一个一开始就指向索引列表n的元素处的ListIterator
package java.util; public interface ListIterator<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] */