关于一个迭代器的问题,求好心人帮忙解答,谢谢了

z252332123 2012-01-15 09:15:15
最近在看JAVA迭代器的问题,有些不理解,请高手们帮忙解答,以下是代码:
import java.util.*;
public class Pet {
public static int i;
public String[] pet = {"dog","cat","mouse","rat","pug"};
public Pet(){
if(i == pet.length)
i = 0;
i++;
}
public String id(){
return pet[i - 1];
}
}
import java.util.*;


public class Tester{
public static void main(String[] args){
ArrayList<String> pets = new ArrayList<String>();
for(int i = 0;i < 6;i++){
pets.add((new Pet()).id());
}
for(int i = 0;i < pets.size();i++){

}

ListIterator<String> it = pets.listIterator();
while(it.hasNext()){
System.out.println(it.previousIndex());
System.out.println(it.nextIndex());
it.next();
}


}
}

编译器输出如下:
-1
0
0
1
1
2
2
3
3
4
4
5


我的问题是:执行it.previousIndex(),首元素的前一个索引是-1,没问题,但他的it.nextIndex()为什么是0,个人觉得应该是1才符合逻辑。求好心人帮忙解释原因,初次发帖,谢谢。
...全文
104 4 打赏 收藏 转发到动态 举报
写回复
用AI写文章
4 条回复
切换为时间正序
请发表友善的回复…
发表回复
dracularking 2012-01-15
  • 打赏
  • 举报
回复
private static class COWIterator<E> implements ListIterator<E> {
/** Snapshot of the array **/
private final Object[] snapshot;
/** Index of element to be returned by subsequent call to next. */
private int cursor;

private COWIterator(Object[] elements, int initialCursor) {
cursor = initialCursor;
snapshot = elements;
}

public boolean hasNext() {
return cursor < snapshot.length;
}

public boolean hasPrevious() {
return cursor > 0;
}

public E next() {
if (! hasNext())
throw new NoSuchElementException();
return (E) snapshot[cursor++];
}

public E previous() {
if (! hasPrevious())
throw new NoSuchElementException();
return (E) snapshot[--cursor];
}

public int nextIndex() {
return cursor;
}

public int previousIndex() {
return cursor-1;
}

/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; <tt>remove</tt>
* is not supported by this iterator.
*/
public void remove() {
throw new UnsupportedOperationException();
}

/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; <tt>set</tt>
* is not supported by this iterator.
*/
public void set(E e) {
throw new UnsupportedOperationException();
}

/**
* Not supported. Always throws UnsupportedOperationException.
* @throws UnsupportedOperationException always; <tt>add</tt>
* is not supported by this iterator.
*/
public void add(E e) {
throw new UnsupportedOperationException();
}
}
dracularking 2012-01-15
  • 打赏
  • 举报
回复
previous和next两者是被设定成相邻的两个元素
虽然在逻辑上可以理解为相隔一个,如果有个假想的中间元素的话
z252332123 2012-01-15
  • 打赏
  • 举报
回复
谢谢了,受C的指针的影响很是不理解,现在懂了。
helloworld_oco 2012-01-15
  • 打赏
  • 举报
回复
迭代器的起始位置在0和-1之间
hasNext为true移到0和1间

62,615

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧