Reputation: 12423
I am a bit stuck trying to implement a method that dynamically initializes a 2D array of objects.
I know to do double brace initialization with a hashmap but in this case i don't want to do that way, i want to learn how to do it manually. I know there has to be a way.
So this is what i have so far, but is not correct:
return new Object[][] {
{
buildNewItem(someValue),
buildNewItem(someValue),
buildNewItem(someValue),
buildNewItem(someValue),
buildNewItem(someValue),
}
};
As you see, I am missing the assignation of the values for the first dimension which should represent the rows(0,1,2,3...).
Could you help me find out how to complete this initialization? Creating the objects before the return statement, is not an option, I want to do it on the go, all together as a single return statement.
Upvotes: 2
Views: 4038
Reputation: 19185
You code is correct but its just for row 0.
You can add more rows using {}
static int count = 0;
public static Integer buildNewItem() {
return count++;
}
public static void main(String[] args) {
System.out.println(Arrays.deepToString(new Object[][]{
{buildNewItem(), buildNewItem(), buildNewItem()},
{buildNewItem(), buildNewItem(), buildNewItem()} <--Use {} to separate rows
}));
}
Output:
[[0, 1, 2], [3, 4, 5]]
Upvotes: 2
Reputation: 32391
Something like this:
return new Object[][] {new Object[]{}, new Object[]{}};
Upvotes: 3
Reputation: 3446
Manually:
Object[][] obj = new Object[ROWS][COLS];
for(int i = 0 ; i < ROWS ; i++) {
for(int j = 0 ; i < COLS; j++) {
obj[i][j] = buildNewItem(someValue);
}
}
Upvotes: 0