我有以下代碼:的Java數組列表,鏈表和堆棧問題
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 2011-03-02 20:12:11
@Boris嗨鮑里斯,我在發佈信息後立即更新了描述,因爲我忘記了包含它 - 現在正確描述。謝謝。 – MusTheDataGuy 2011-03-02 20:13:25
太好了。雖然現在已經發布了答案:-) – Boris 2011-03-02 20:17:53