最近在看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才符合逻辑。求好心人帮忙解释原因,初次发帖,谢谢。
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才符合逻辑。求好心人帮忙解释原因,初次发帖,谢谢。
hasNext为true移到0和1间
虽然在逻辑上可以理解为相隔一个,如果有个假想的中间元素的话
/** 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();
}
}