Buki
Buki

Reputation: 127

populating 2d array with two 1d arrays in java

I have 2 1d arrays and im trying to populate them into a single 2d array in JAVA.

For instance:

x[] = {2,5,7,9}
y[] = {11,22,33,44}

The results should then be:

result[][] = {{2,5,7,9}, {11,22,33,44}}

How do I go about this? I currently have something like this:

for(int row = 0; row < 2; row++) {
    for(int col = 0; col == y.length; col++) {
        ???
    }
}

Im sort of stuck from there...

Upvotes: 6

Views: 12884

Answers (3)

Juvanis
Juvanis

Reputation: 25950

2D array is an array of arrays. So why don't you try this?

int result[][] = {x,y};

And to make sure that it is so simple and works, test this:

for(int i=0; i<result.length; i++)
{
    for(int j=0; j<result[0].length; j++)
        System.out.print(result[i][j]+ " ");
    System.out.println();
}

Upvotes: 15

Baris Akar
Baris Akar

Reputation: 4965

Try this:

ArrayList<Integer[]> tempList = new ArrayList<Integer[]>();

tempList.add(x);
tempList.add(y);

Integer result[][] = new Integer[tempList.size()][];
result = tempList.toArray(tempList);

Upvotes: 3

Sunil Kumar B M
Sunil Kumar B M

Reputation: 2795

You have to revert the row and column indices

for(int row = 0; row < 2; row++)
{
    for(int col = 0; col = y.length; col++)
    {
        ....
    }
}

Upvotes: 1

Related Questions