我來自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) –
爲什麼不使用構造函數,如果你只需要初始化它 –