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);
}
最佳答案
您需要初始化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
实例的数组 - 您需要单独初始化每个实例。
关于java - 为什么在 Java 中使用数组时会出现 NullPointerException?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9509331/