带基数排序的NullPointerException

时间:2009-12-24 14:00:41

标签: java algorithm sorting

我尝试编写基数排序,但运行此代码时出现NullPointerException

public class ThreeRadixSort {

    public Queue getSortedData(Queue queue){
        Queue array[] = new Queue[10];

        for(int i=1;i<=3;i++){

        while(queue.front != null){
            Student student = queue.dequeue();

            if( i == 1) 
                array[(int)(student.id%10)].enqueue(student);
            else if( i == 2)
                array[(int)((student.id%100)/10)].enqueue(student);
            else    
                array[(int)(student.id/100)].enqueue(student);

        }

        for(int j=0;j<=9;j++){

        while( array[j] != null && array[j].front != null)
            queue.enqueue(array[j].dequeue());
        }
        }   
        return queue;
    }
}

当工具到达

时显示异常
    array[(int)(student.id%10)].enqueue(student);

2 个答案:

答案 0 :(得分:2)

这里的问题是,当您初始化Queue数组时,每个点都会初始化为null。现在,您正试图在enqueue上调用null方法。您需要循环遍历数组的每个位置并为其分配new Queue()或者初始化它们。

例如:

for (int i = 0; i < array.length; i++) {
  array[i] = new Queue();
}

答案 1 :(得分:1)

这一行:

 Queue array[] = new Queue[10]

仅声明一个队列数组。它不会自己分配队列。 你应该像这样初始化它们:

 for(int i; i<10; i++)
 {
      array[i] = new Queue();
 }

P.S。顺便说说。而不是依赖像'10'这样的神奇数字,最好让它成为常量并在程序的顶部声明。像这样:

 const int numElements = 10;