Dre*_*iak 0 java linked-list nullpointerexception
这个问题可能是一个简单的解决方案,我整晚都在这里.至少我希望有.当试图向我的subQueues LinkedList提供一个对象时,我收到一个NullPointerException.我的程序打印出正确的"头"对象和"数字"整数,但随后抛出异常并结束程序.
简而言之,我的程序应该采用一个mainQueue LinkedList的整数,逐个查看它们,并对它们进行排序.它检查每个整数的最后一位数,并将它们放入相应的subQueues中.截至目前,我只到那个地方.在我克服了这个困境后,我将能够计算出数十,数百等.
例)
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 }
Run Code Online (Sandbox Code Playgroud)
那么我在这里做错了什么?就像我说的,一旦我遇到这个小问题,程序的其余部分应该是轻而易举的.任何帮助表示赞赏,谢谢!
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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
你没有正确地构建subQueues它看起来像.如果你想要一个SIZE链表列表,试试这个:
subQueues = new LinkedList[ SIZE ];
for ( int i = 0; i < SIZE; ++i ) {
subQueues[i] = new LinkedList();
}
Run Code Online (Sandbox Code Playgroud)
请注意,这是使用原始类型作为代码,但最好是使用参数化类型.