我来自C背景,并且正在运行Java中的问题。目前,我需要在一个对象数组中初始化一个变量数组。在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
。我做错了什么,有没有更好的方法来做到这一点?
你需要的路线[I]路线之前=新干线()[我] .departureTimes = new int [count]; – aviad
[李尔在这里](http://www.tutorialspoint.com/java/java_arrays.htm) –
为什么不使用构造函数,如果你只需要初始化它 –