gpt4 book ai didi

java - 在Java中的类实例中初始化变量数组

转载 作者:塔克拉玛干 更新时间:2023-11-02 07:51:36 26 4
gpt4 key购买 nike

我有 C 语言背景,但在 Java 中遇到了问题。目前,我需要在一个对象数组中初始化一个变量数组。

我知道在 C 中它类似于 malloc-ing structs 数组中的 int 数组,例如:

typedef struct {
char name;
int* times;
} Route_t

int main() {
Route_t *route = malloc(sizeof(Route_t) * 10);
for (int i = 0; i < 10; i++) {
route[i].times = malloc(sizeof(int) * number_of_times);
}
...

到目前为止,在 Java 中我有

public class scheduleGenerator {

class Route {
char routeName;
int[] departureTimes;
}

public static void main(String[] args) throws IOException {
/* code to find number of route = numRoutes goes here */
Route[] route = new Route[numRoutes];

/* code to find number of times = count goes here */
for (int i = 0; i < numRoutes; i++) {
route[i].departureTimes = new int[count];
...

但它会吐出一个 NullPointerException。我做错了什么,是否有更好的方法来做到这一点?

最佳答案

初始化数组时

Route[] route = new Route[numRoutes];

numRoutes 个插槽都填充了它们的默认值。对于引用数据类型,默认值为 null,因此当您尝试在第二个 for 循环中访问 Route 对象时,它们都是 null,你首先需要像这样初始化它们:

public static void main(String[] args) throws IOException {
/* code to find number of route = numRoutes goes here */
Route[] route = new Route[numRoutes];

// Initialization:
for (int i = 0; i < numRoutes; i++) {
route[i] = new Route();
}

/* code to find number of times = count goes here */
for (int i = 0; i < numRoutes; i++) {
// without previous initialization, route[i] is null here
route[i].departureTimes = new int[count];

关于java - 在Java中的类实例中初始化变量数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13985430/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com