繁体   English   中英

为什么在Java中使用数组获取NullPointerException?

[英]Why am I getting a NullPointerException with arrays in Java?

public static byte[] main_Mem = new byte[2048];
public static SlotNode[] cache = new SlotNode[8];

这不是创建对象的实例吗? 为什么我要获得NPE?

 //initialize main memory
           for (int i = 0; i<main_Mem.length; i++) {
                   main_Mem[i] = (byte) (0xFF & i);
                   System.out.printf("%X", 0xFF & i);
                   System.out.print("      " + i);
                   System.out.println(" ");

           }

           //initialize cache slots to 0
           for (int i = 0; i<cache.length; i++) {
                   cache[i].setValidBit(0);
                   cache[i].setTag(0);
                   cache[i].setData(0);
                   cache[i].setDirty(0);
           }

不,为数组分配内存与分配对象不同。

数组缓存具有8个SlotNode类型的引用,所有这些引用都设置为null,直到您将它们分配为指向SlotNode实例为止。

您需要初始化SlotNode,例如:

   for (int i = 0; i<cache.length; i++) {
           cache[i] = new SlotNode(...); // Add the constructor parameters as needed
           cache[i].setValidBit(0);
           cache[i].setTag(0);
           cache[i].setData(0);
           cache[i].setDirty(0);
   }

通过做这个:

public static SlotNode[] cache = new SlotNode[8];

您只需初始化8个SlotNode实例的数组 -您需要分别初始化每个实例。

这个:

new SlotNode[8]

仅创建8个SlotNode引用的数组。 默认情况下,它们都初始化为null ,因此您稍后必须自己对其进行初始化。 例如,在循环中:

for (int i = 0; i<cache.length; i++) {
    cache[i] = new SlotNode(); // initialize the object
    cache[i].setValidBit(0);
    cache[i].setTag(0);
    cache[i].setDirty(0);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM