public class BusInformation {
String BusRoute[][] = new String[4][];
BusRoute[0] = new String[] {"a" , "b", "c"};
BusRoute[1] = new String[] {"a" , "b"};
}
I know how many BusRoutes are there as in first parameter. The second parameters size is variable and depends on the route.
How can I initialize it this way?
You should be able to code it like this…
Its the same as your code, but like to specify an initial size of
0for the second dimension, just so its clear that it doesn’t have any initial size. I also wrapped the loading of the array into the class constructor.A 2D array is just a normal 1D array where each item is an array of any length. Even if you set the 2D array at an initial size, such as
new String[4][5], it won’t make any difference – you can still assign smaller or larger arrays to each item of the base array, just as you are doing already.