Ryan Sayles
Ryan Sayles

Reputation: 3441

Java 2D array copy

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!

Upvotes: 0

Views: 1893

Answers (2)

cyon
cyon

Reputation: 9548

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.

Upvotes: 5

Adude11
Adude11

Reputation: 605

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

Upvotes: 2

Related Questions