Vedran
Vedran

Reputation: 43

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?

With this code im getting error "non-static method someFunction() cannot be refferenced from static content ---"(netbeans) on line data[a] = someFunction();

Upvotes: 1

Views: 918

Answers (2)

Tim Hallyburton
Tim Hallyburton

Reputation: 2929

Change your someFunction() by adding "static".

You also should consider using an ArrayList for such tasks, those are dynamic and desinged for your purpose (I guess).

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

Upvotes: 0

Eran
Eran

Reputation: 393781

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.

Of course, your someFunction returns an array of null references, so you still have to initialize the Strings of that array in some loop.

I just noticed the error you got. Change your someFunction to be static.

Upvotes: 1

Related Questions