Java 中 ListIterator 接口的使用示例
参考资料:
《Thinking in Java Fourth Edition》 作者:Bruce Eckel
package holding;
import java.util.*;
public class ListIteration {
public static void main(String[] args) {
Random random = new Random(47);
Integer[] integers = {
random.nextInt(47),
random.nextInt(47),
random.nextInt(47),
random.nextInt(47),
random.nextInt(47),
random.nextInt(47),
random.nextInt(47),
random.nextInt(47)
};
List<Integer> list = Arrays.asList(integers);
ListIterator<Integer> it = list.listIterator();
System.out.println(it.previousIndex()); //迭代器在列表的开始,则返回 -1
while(it.hasNext()) {
//当迭代器在列表结尾,nextIndex() 方法则返回列表的大小
System.out.print("{" + it.next() + ", " + it.nextIndex() + ", " + it.previousIndex() + "} ");
}
System.out.println();
// 向前迭代:
while(it.hasPrevious()) {
System.out.print(it.previous() + ", ");
}
System.out.println();
System.out.println(Arrays.asList(integers));
//指定索引向后迭代
it = list.listIterator(3);
while (it.hasNext()) {
it.next();
it.set(random.nextInt(47)); //替换 it.next() 返回的元素
}
System.out.println(Arrays.asList(integers));
//指定索引向前迭代
it = list.listIterator(5);
while (it.hasPrevious()) {
it.previous();
it.set(random.nextInt(47)); //替换 it.previous() 返回的元素
}
System.out.println(Arrays.asList(integers));
}
} /* Output:
-1
{8, 1, 0} {21, 2, 1} {5, 3, 2} {6, 4, 3} {21, 5, 4} {39, 6, 5} {33, 7, 6} {2, 8, 7}
2, 33, 39, 21, 6, 5, 21, 8,
[8, 21, 5, 6, 21, 39, 33, 2]
[8, 21, 5, 36, 39, 24, 16, 3]
[21, 38, 12, 20, 12, 24, 16, 3]
*///:~