6

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

3 Answers 3

15

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();
}
Sign up to request clarification or add additional context in comments.

1 Comment

:) Why people are giving other answers. +1 for this one.
3

Try this:

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

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

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

1 Comment

the arraylist is just a temporary container for the arrays. you can add multiple arrays of different sizes to the arraylist and get the corresponding 2D-array from it afterwards using toArray(). but the answer of deporter is clearly simpler if it fits your needs.
1

You have to revert the row and column indices

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.