Reputation: 378
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?
Upvotes: 0
Views: 6147
Reputation: 719436
If you are asking about a hard-wired initialization, your code could be written more concisely as this:
public class BusInformation {
String BusRoute[][] = new String[][]{
{"a" , "b", "c"},
{"a" , "b"},
null,
null
};
}
But beware that there are hard limits on how much initialization a method of constructor can do. (It is to do with the fact that a method's bytecodes have to fit into 64k bytes.)
If you are asking about initializing the array from (say) stuff read from a file, then it is basically a matter of working out how big the arrays need to be, creating them, and filling in their values. (For instance, you might read the data into a list-of-lists and then convert to the 2-D array form.
Upvotes: 0
Reputation: 32969
If the size is variable and unknown at initialization, maybe an array is not the best option here. I have two suggestions, one use an array of Lists
or use Guava's Multimap
If you really want to / need to continue to use a two dimensional array, initialize it as described above (either with the first set of elements or as an empty array) and when you need to add values, use Arrays.copyOf to create a copy of the array with a new size to allow for adding the new elements.
Upvotes: 0
Reputation: 8774
You should be able to code it like this...
public class BusInformation {
String busRoute[][] = new String[4][0];
public BusInformation(){
busRoute[0] = new String[] {"a" , "b", "c"};
busRoute[1] = new String[] {"a" , "b"};
}
}
Its the same as your code, but like to specify an initial size of 0
for 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.
Upvotes: 1