索引,元素下标,Java ListIterator 中的 nextIndex() 和 next();

索引,元素下标,Java ListIterator 中的 nextIndex() 和 next();

问题

previousIndex():输出前一个元素的下标(索引)
nextIndex():输出下一个元素的下标(索引)

public static void main(String[] args) {
ArrayList c0 = new ArrayList();
c0.add(“10”);
c0.add(“20”);
c0.add(“30”);
ListIterator it = c0.listIterator()
while (it.hasNext()) {
System.out.println(it.next() + ", " + it.previousIndex() + ", " + it.nextIndex());
}}
运行以上代码
结果:

10,0,1

20,1,2

30,2,3

按照惯有的,数组下标从0开始 ,10的下标是0,那么10的前一个元素索引 不应该是-1吗?
那会不会由于10之前没元素,所以就默认10的前一个元素就是自己呢?
接着看第二行输出
20 的上一个元素的下标是1,额,10在20前面,10的下标是0啊,额?
接着看

以下是个人观点,未验证源码的具体实现机制。

代码

package DataBase;
import java.util.*;
public class TestIterator {

public static void main(String[]args)
{
	ArrayList<String>c0=new ArrayList<>();
	c0.add("0");
	c0.add("1");
	c0.add("2");
	c0.add("3");
	ListIterator<String>it=c0.listIterator();
	    
	System.out.print(c0+"test1\n");
	System.out.print(it.previousIndex()+"\n");
	System.out.print(it.nextIndex()+"\n");
	
	System.out.print(c0+"test2\n");
	it.next();
	System.out.print(it.previousIndex()+"\n");
	System.out.print(it.nextIndex()+"\n");
	
	System.out.print(c0+"test3\n");
	it.add("111");		
	System.out.println(c0);
	System.out.print(it.previous()+"\n");
	System.out.print(it.previousIndex()+"\n");
	System.out.print(it.nextIndex()+"\n");
	
	System.out.print(c0+"test4\n");
	it.next();
	it.previous();
	it.add("222111");	
	System.out.print(c0+"\n");
	System.out.print(it.previousIndex()+"\n");
	System.out.print(it.nextIndex()+"\n");
	
	
	
}

}

输出

[0, 1, 2, 3]test1
-1
0
[0, 1, 2, 3]test2
0
1
[0, 1, 2, 3]test3
[0, 111, 1, 2, 3]
111
0
1
[0, 111, 1, 2, 3]test4
[0, 222111, 111, 1, 2, 3]
1
2

理解

结合代码与输出,ListIterator对象 其实就是一个游标,(游标嘛,比如你打字的那一条竖线)

看一下这张图:

在这里插入图片描述
从代码和输出看,结合猜想,调用next()会使游标右移一位,同理调用previous()游标左移一位;同时这两个函数还会返回游标扫过的元素(即游标向前动,返回没动时的前一个元素,向后动返回没动时后一个元素)

test1中游标位置如图,所以
previousIndex():-1 (next()也会返回一个最大的为n的index (a[n]) 这里一直用 next();当hasnext()==false时 ,nextIndex()返回值为 n ;实际上下标最大为n-1)
nextIndex(): 0

test2同理
test3和test4用图片下的几句话去理解

推广到常见的其他的next()或previous()方法;关于游标,大致如此,具体如何,请自行验证

以上,可能很巧解决了你的问题,如果看不懂或没用,那也正常

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值