调整数组大小时出现空指针异常

时间:2014-11-19 14:04:28

标签: java arrays nullpointerexception null

我在行中有NullPointerException" newIndexer[i].index = (int)Double.POSITIVE_INFINITY;"我无法弄清楚为什么。非常感谢任何帮助。

    public void resizeIndexer(int newKey)
    {   
        if (maxHeap >= newKey)
            return;
        if (newKey > maxHeap){
            Handle[] newIndexer = new Handle[newKey + 1];
            for (int i = 0; i < newKey; i++){
                if (i < maxHeap)
                newIndexer[i] = this.Indexer[i];
                else{
                    System.out.println(i);
                    newIndexer[i].index = (int)Double.POSITIVE_INFINITY;
                    newIndexer[i].status = false;
                }
            }       
            maxHeap = newKey;
            Indexer = newIndexer;
        }
    }

1 个答案:

答案 0 :(得分:1)

在修改indexstatus成员之前,您必须为新数组的每个新索引创建一个新的Handle实例:

        for (int i = 0; i < newKey; i++){
            if (i < maxHeap)
                newIndexer[i] = this.Indexer[i];
            else{
                System.out.println(i);
                newIndexer[i] = new Handle ();
                newIndexer[i].index = (int)Double.POSITIVE_INFINITY;
                newIndexer[i].status = false;
            }
        }