0
對於我整晚都會遇到的這個問題,可能有一個簡單的解決方案。至少我希望有。當試圖向我的subQueues LinkedList提供一個對象時,我收到一個NullPointerException異常。我的程序打印出正確的「頭」對象和「數字」整數,但隨後拋出異常並且程序結束。Java - 在向LinkedList提供對象時接收NullPointerException
我的程序,總之,應該採取一個mainQueue LinkedList的整數,逐個查看它們,並對它們進行排序。它檢查每個整數的最後一位,並將它們放入相應的子隊列中。到現在爲止,我只是在那個地方。我突破這個困境後,我就可以工作了幾十個,幾百等
例)
mainQueue = { 12 50 215 100 85 539 16 35 }
subQueue[0] = { 50 100 }
subQueue[1] = { }
subQueue[2] = { 12 }
subQueue[3] = { }
subQueue[4] = { }
subQueue[5] = { 215 85 35 }
subQueue[6] = { 16 }
subQueue[7] = { }
subQueue[8] = { }
subQueue[9] = { 539 }
那我錯在這裏做什麼?就像我說的,一旦我遇到這個小問題,程序的其餘部分應該變得輕而易舉。任何幫助表示讚賞,謝謝!
public class Sorting
{
private LinkedList mainQueue;
private LinkedList[] subQueues;
private final int SIZE = 10;
private int maxDigits; //maximum number of digits
//The constructor instantiates the mainQueue using the LinkedList,
//subQueue array as an array of LinkedList using SIZE(10),
//and initializes maxDigits = 0;
public Sorting()
{
mainQueue = new LinkedList();
for (int i=0; i<SIZE; i++)
{
subQueues = new LinkedList[i];
}
// I have also tried:
// subQueues = new LinkedList[SIZE];
//I get the same runtime error.
maxDigits = 0;
}
public void sortNumbers()
{
while (mainQueue.isEmpty() == false)
{
Object head = mainQueue.peek();
mainQueue.remove();
String digitLine = "" + head;
int digit = Integer.parseInt(digitLine.substring(digitLine.length()-1, digitLine.length()));
System.out.println(head);
System.out.println(digit);
subQueues[digit].offer(head);
}
}
}
謝謝!這就是訣竅,我知道它必須是那樣簡單的東西。欣賞它=] – Dreiak
參數化類型的數組是非法的:) – Affe
是的,實例化一個是,但他仍然可以保持其聲明參數化,並使其類型安全。 –