简体   繁体   中英

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.

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.

像这样:

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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