源码是:
public class CollectionSequence extends AbstractCollection<Pet>{
private Pet[] pets = new Pet[8];
public static void main(String[] args) {
CollectionSequence cs = new CollectionSequence();
Iterator<Pet> it = cs.iterator();
while(it.hasNext()) {
it.next().display();
}
}
@Override
public Iterator<Pet> iterator() {
return new Iterator<Pet>(){
private int index = 0;
public boolean hasNext() {
return index<pets.length;
}
public Pet next() {return pets[index++];}
public void remove() {
try {
throw new Exception();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
};
}
@Override
public int size() {毕业论文
// TODO Auto-generated method stub
return pets.length;
}
}
class Pet{
public Pet(){
}
public void display() {
System.out.println("hello world!");
}
}
异常栈:
Exception in thread "main" java.lang.NullPointerException
at cn.richinfo.collection.CollectionSequence.main(CollectionSequence.java:19)
private Pet[] pets = new Pet[8];
你这只是声明了一个对象数组
并未赋值啊,当然是NULL了