简体   繁体   English

如何动态初始化2D对象数组

[英]How to initialize dynamically a 2d object array

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. 我知道一定有办法。

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...). 如您所见,我缺少第一个维的值分配,该维应该表示行(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语句之前创建对象不是一种选择,我想随时随地将其作为单个return语句一起执行。

像这样:

    return new Object[][] {new Object[]{}, new Object[]{}};

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]]

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);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM