简体   繁体   English

Java如何以编程方式初始化2d对象数组?

[英]Java how to programmatically initialize 2d object array?

Object[][] dataEntriesg = {
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
        {"","","","",""},
};

I want to initialize 2d array such as this. 我想初始化这样的二维数组。 the way I am doing it is so stupid. 我这样做的方式是如此愚蠢。 How can I use a loop to do it? 如何使用循环来做到这一点? I have tried to put it in for loop. 我试图将其放入for循环中。 But seems {} can be used only at declaration. 但似乎{}仅可在声明时使用。

You could use a compound for-loop , something like... 您可以使用复合for-loop ,例如...

dataEntriesg = new Object[25][5];
for (int row = 0; row < dataEntriesg.length; row++) {
    for (int col = 0; col < dataEntriesg[row].length; col++) {
        dataEntriesg[row][col] = "";
    }
}

...for example ...例如

Used my sample as a blue print 将我的样品用作蓝图

For example , suppose x = new int[3][4] , x[0] , x[1] , and x[2] are one-dimensional arrays and each contains four elements, as shown in the figure x.length is 3 , and x[0].length , x[1].length , and x[2].length are 4 例如 ,假设x = new int[3][4] x[0] x[1]x[2]是一维数组,并且每个包含四个元件,如该图所示x.length3x[0].lengthx[1].lengthx[2].length4

在此处输入图片说明

How to traverse and intilize the 2D array you can follow following sample as your blue print : 如何遍历和利用2D数组,您可以遵循以下示例作为蓝图

在此处输入图片说明

for (int i = 0; i < dataEntriesg.length ; i++) {
    Arrays.fill(dataEntriesg [i], "");
}

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

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