Java 中 ListIterator 接口的使用示例

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]
*///:~


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值