1

i want to initialize an array from another multidimensional array. The thing is i don't want the elements, the second array only needs to be the same size.

like i have

int table[1][2];
table[0][0] = '1';
table[0][1] = '2';
table[0][2] = '3';
table[1][0] = '4';
table[1][1] = '5';
table[1][2] = '6';
} 

and i need:

 int copyofthetable[1][2];

    copyofthetable[0][0] = '0';
    copyofthetable[0][1] = '0';
    copyofthetable[0][2] = '0';
    copyofthetable[1][0] = '0';
    copyofthetable[1][1] = '0';
    copyofthetable[1][2] = '0';

i have tried arraycopy but it copies the elements as well. note that i don't have the size of the first array beforehand and its given later. thanks :)

1
  • Try table.length and table[0].length (assuming the first length is > 0) Commented Sep 3, 2015 at 14:26

1 Answer 1

5

If you only need an array of the same size :

int[][] copyofthetable = new int[table.length][table[0].length];

This is assuming all the rows of the table array have the same length. If that's not the case, you'll need a loop :

int[][] copyofthetable = new int[table.length][];
for (int i = 0; i < table.length; i++)
    copyofthetable[i] = new int[table[i].length];
Sign up to request clarification or add additional context in comments.

5 Comments

Wouldn't this only work if the table[0].length is the same as table[1].length?
@Turtle Yep, I just added a comment about that.
@Turtle according to how the question was asked (at least in the example provided) it would be. Good observation nonetheless.
Thanks @Eran! I was just wondering if looping is the most efficient way as there are some complexity checks later on in our system.
@user1972584 You have no other choice if your source 2D array has rows of varying lengths. If you use System.arraycopy, you will be copying references of the original inner arrays (the rows of the original array), so even if you didn't mind copying the int values, you'd still have a problem (since target[1][2]=3 would also modify source[1][2]).

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.