简体   繁体   English

Java用1D数组填充2D数组

[英]Java fill 2d array with 1d arrays

Whats the nicest way to fill up following array: 填充以下数组的最好方法是什么:
From main: 从主要:

String[][] data = new String[x][3]; 

for(int a = 0; a < x; a++){ 
    data[a] = someFunction();
}

Function I am using..: 我正在使用的功能..:

 public String[] someFunction(){
     String[] out = new String[3];

     return out;
 }

Is it possible to do something like this? 有可能做这样的事情吗? Or do I have to fill it with for-loop? 还是我必须用for循环填充它?

With this code im getting error "non-static method someFunction() cannot be refferenced from static content ---"(netbeans) on line data[a] = someFunction(); 有了这段代码,出现错误“非静态方法someFunction()不能从静态内容中引用---“(netbeans)在线data[a] = someFunction();

You have to specify how many rows your array contains. 您必须指定数组包含多少行。

String[][] data = new String[n][];

for(int i = 0; i < data.length; i++){
    data[i] = someFunction();
}

Note that someFunction can return arrays of varying lengths. 注意someFunction可以返回不同长度的数组。

Of course, your someFunction returns an array of null references, so you still have to initialize the String s of that array in some loop. 当然, someFunction返回一个空引用数组,因此您仍然必须在某个循环中初始化该数组的String

I just noticed the error you got. 我只是注意到您遇到的错误。 Change your someFunction to be static. 将您的someFunction更改为静态。

Change your someFunction() by adding "static". 通过添加“静态”来更改someFunction()。

You also should consider using an ArrayList for such tasks, those are dynamic and desinged for your purpose (I guess). 您还应该考虑将ArrayList用于此类任务,这些任务是动态的并且是为您的目的设计的(我想)。

public static void main(String[] args){

    int x = 3;

    String[][] data = new String[x][3]; 

    for(int a = 0; a < x; a++){ 
        data[a] = someFunction();
    }

}

public static String[] someFunction(){
     String[] out = new String[3];
     return out;
 }

Greetings Tim 蒂姆的问候

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

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