【发布时间】:2011-03-02 20:08:53
【问题描述】:
我有以下代码:
public static void printCollection(ArrayList<Data> al, LinkedList<Data> ll, Stack<Data> stack){
for(Iterator<Data> iter = al.iterator(); iter.hasNext();){
Data x = (Data)iter.next();
x.print();
}
System.out.println();
}
public static void main(String[] args){
Data x = new Data("Fred", 41);
x.print();
//ArrayList
ArrayList<Data> arrayList = new ArrayList<Data>();
//LinkedList
LinkedList<Data> linkedList = new LinkedList<Data>();
//Stack
Stack<Data> stack = new Stack<Data>();
//'people' variables
Data person1 = new Data("Fred", 21);
Data person2 = new Data("Jane", 21);
Data person3 = new Data("Zoe", 23);
Data person4 = new Data("Harry", 78);
//ArrayList
arrayList.add(person1);
arrayList.add(person2);
arrayList.add(person3);
arrayList.add(2, person4);
printCollection(arrayList, null, null);
//LinkedList
linkedList.add(person1);
linkedList.add(person2);
linkedList.add(person3);
linkedList.add(2, person4);
printCollection(null, linkedList, null);
//Stack
stack.push(person1);
stack.push(person2);
stack.push(person3);
stack.push(person4);
while(stack.isEmpty() == false)
{
stack.pop().print();
}
System.out.println(stack.size());
}
...产生 NullPointerException 错误。但是,如果我删除一些代码使其看起来像这样:
public static void printCollection(ArrayList<Data> al, LinkedList<Data> ll, Stack<Data> stack){
for(Iterator<Data> iter = al.iterator(); iter.hasNext();){
Data x = (Data)iter.next();
x.print();
}
System.out.println();
}
public static void main(String[] args){
Data x = new Data("Fred", 41);
x.print();
//ArrayList
ArrayList<Data> arrayList = new ArrayList<Data>();
//LinkedList
LinkedList<Data> linkedList = new LinkedList<Data>();
//Stack
Stack<Data> stack = new Stack<Data>();
//'people' variables
Data person1 = new Data("Fred", 21);
Data person2 = new Data("Jane", 21);
Data person3 = new Data("Zoe", 23);
Data person4 = new Data("Harry", 78);
//ArrayList
arrayList.add(person1);
arrayList.add(person2);
arrayList.add(person3);
arrayList.add(2, person4);
printCollection(arrayList, null, null);
}
}
...然后它运行得很好。我已经检查了多次,但无法检测到错误(没有双关语(NullPointerException))。
错误一直出现在以下行:
for(Iterator<Data> iter = al.iterator(); iter.hasNext();){
//remaining code omitted for illustration purposes
我不知道它可能是什么,需要一些新鲜的眼睛来帮助我看看。
感谢您抽出宝贵时间阅读本文。
米克
【问题讨论】:
-
堆栈跟踪说明了什么?在哪一行抛出异常?
-
@Boris 嗨,鲍里斯,我一发布信息就更新了描述,因为我忘记了包含它 - 现在描述正确。谢谢。
-
太棒了。虽然现在已经发布了答案:-)
标签: java stack arraylist linked-list