日期:2014-05-20  浏览次数:20766 次

实现AbstractCollection出现空指针异常
源码是:
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)

------解决方案--------------------
引用:
源码是:
public class CollectionSequence extends AbstractCollection<Pet>{

private Pet[] pets = new Pet[8];

public static void main(String[] args) {
CollectionSequence cs = new Collect……


private Pet[] pets = new Pet[8];
你这只是声明了一个对象数组
并未赋值啊,当然是NULL了