我用Java编写了一个模拟,但是在运行时遇到了一些问题。我创建的用于模拟模型各方面的自定义类似乎从未被初始化。例如,
public class Queue {
public static int front = -1;
public static int length = 0;
public static int capacity = 0;
public static int roadqueue[];
public static int position[];
public static boolean full = false;
public static void push(int pushValue) {
然后是可以从类运行的函数。
在我的主项目中,我声明该类如下:
public class myProject {
public static Queue queue[] = new Queue[33];
然后在主函数中,我首先调用一个应该初始化此类中的值的函数:
public static void main(String[] args) {
initQueue();
与
public static void initQueue() {
queue[0].length = 6000;
queue[14].length = 6000;
queue[1].length = 20;
queue[13].length = 20;
queue[3].length = 10;
queue[11].length = 10;
queue[4].length = 360;
queue[12].length = 360;
queue[5].length = 260;
queue[10].length = 260;
queue[6].length = 20;
queue[9].length = 400;
queue[15].length = 460;
queue[22].length = 460;
queue[16].length = 260;
queue[21].length = 260;
queue[17].length = 100;
queue[26].length = 100;
queue[18].length = 160;
queue[20].length = 140;
queue[23].length = 240;
queue[25].length = 140;
queue[27].length = 80;
queue[32].length = 80;
queue[28].length = 480;
queue[31].length = 140;
for (int i = 0; i < 33; i++) {
if (i == 3 || i == 12)
queue[i].capacity = 40;
else
queue[i].capacity = queue[i].length / 10;
queue[i].position = new int[queue[i].capacity];
queue[i].roadqueue = new int[queue[i].capacity];
}
}
但是,当我运行项目并插入断点时,for 循环开始迭代,但 Netbeans 通知我,例如在
queue[0].length = 6000;
“length 引用了一个 null 对象”,并且在变量资源管理器中,queue[] 中的所有值在整个程序中都保持为 null。知道我做错了什么吗?
最佳答案
数组的所有元素都会自动初始化为其默认值(在您的情况下为 null
)。您有一个包含 33 个空 Queue
的数组。
正如其他人所建议的,您需要在使用元素之前为其分配一个 Queue
实例
queue[i] = new Queue();
//now you can use queue[i]
LE:顺便说一句,我怀疑您希望 Queue
中的这些字段是static
。您正在创建一个Queue
数组,它们都具有相同的字段。您可能希望从这些字段中删除 static
关键字(这可能还包括从某些 Queue
方法中删除 static
)。
关于java - 为什么我创建的对象保持为 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20563004/