简体   繁体   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];

Doesn't this create instances of the objects? 这不是创建对象的实例吗? Why would I be getting a NPE? 为什么我要获得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);
           }

No, allocating memory for the arrays is not the same thing as allocating objects. 不,为数组分配内存与分配对象不同。

The array cache has 8 references of type SlotNode, all set to null until you assign them to point to a SlotNode instance. 数组缓存具有8个SlotNode类型的引用,所有这些引用都设置为null,直到您将它们分配为指向SlotNode实例为止。

You need to init the SlotNode, such as this: 您需要初始化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);
   }

By doing this: 通过做这个:

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

you just initialize the array of 8 SlotNode instances - you need to initialize each of them separately. 您只需初始化8个SlotNode实例的数组 -您需要分别初始化每个实例。

This: 这个:

new SlotNode[8]

Only creates an array of 8 SlotNode references. 仅创建8个SlotNode引用的数组。 They're all initialized to null by default, so you have to initialize them yourself later. 默认情况下,它们都初始化为null ,因此您稍后必须自己对其进行初始化。 For instance, in the loop: 例如,在循环中:

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