I am a bit stuck trying to implement a method that dynamically initializes a 2D array of objects.
我在尝试实现动态初始化2D对象数组的方法时遇到了一些困难。
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.
我知道用hashmap做双括号初始化,但是在这种情况下,我不想那样做,我想学习如何手工做。我知道总有办法的。
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...).
如您所见,我缺少第一个维度的值的assignation,它应该表示行(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.
你能帮我找到如何完成这个初始化吗?在return语句之前创建对象,不是一个选项,我想在运行时创建对象,所有这些都作为一个返回语句一起创建。
3 个解决方案
#1
3
Something like this:
是这样的:
return new Object[][] {new Object[]{}, new Object[]{}};
#2
2
You code is correct but its just for row 0. You can add more rows using {}
您的代码是正确的,但它只是用于第0行。可以使用{}添加更多行
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]]
#3
0
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);
}
}
#1
3
Something like this:
是这样的:
return new Object[][] {new Object[]{}, new Object[]{}};
#2
2
You code is correct but its just for row 0. You can add more rows using {}
您的代码是正确的,但它只是用于第0行。可以使用{}添加更多行
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]]
#3
0
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);
}
}