0

I have a 2D array and I just need to copy the first row into another array of the same size. What is the best way of doing this? I tried this:

public static int[][] buildCME(int[][] array){ int [][] arrayCME = new int[array.length][array[0].length]; for(int y = 1; y < array.length; y++) { for (int x = 0; x < 1; x++) { arrayCME[y][x] = array[y][x]; } } 

However that is just giving me 0's for the first row, which I assume has to do with my int initialization. I created this for loop because I thought it would be easier to account for than to create an if statement in a normal for loop to account for the whole 2D array. Thanks for the help!

2 Answers 2

5

Your code copies the first column (your inner loop is x < 1) starting from the second row (outer loop starts at 1). If you want to copy the first row do

 for (int x = 0; x < array[0].length; x++) { arrayCME[0][x] = array[0][x]; } 

To do this more efficiently, you might want to have a look at System.arraycopy:

System.arraycopy(array[0],0,arrayCME[0],0,array[0].length); 

System.arraycopy should perform a more efficient copy since it is a native method. Furthermore, some JVMs like for example the HotSpot JVM treat this method as an intrinsic. A JVM will usually substitute calls to intrinsics methods with architecture specific code, which in the case of arraycopy might be machine code that copies memory directly.

Sign up to request clarification or add additional context in comments.

Comments

2

It's because your outer loop begins on 1, not 0 and as arrays start at 0, the first row will always be unchanged.

2 Comments

That's what I want to happen, for it to not be changed, but when I print out arrayCME it's all 0's for the first row
What @Aaron means is that the first row of arrayCME will be unchanged from the default -- which is all zeroes -- which is not what you want. Make the outer loop start at 0.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.