copy a 2d array in java

Posted on

Problem :

i have a 2d array called matrix of type int that i want to copy to a local variable in a method so i can edit it

whats the best way to copy the array, i am having some troubles

for example

    int [][] myInt;
    for(int i = 0; i< matrix.length; i++){
        for (int j = 0; j < matrix[i].length; j++){
            myInt[i][j] = matrix[i][j];
        }
    }

    //do some stuff here
    return true;
}

Solution :

There are two good ways to copy array is to use clone and System.arraycopy().

Here is how to use clone for 2D case:

int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
    myInt[i] = matrix[i].clone();

For System.arraycopy(), you use:

int [][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
  int[] aMatrix = matrix[i];
  int   aLength = aMatrix.length;
  myInt[i] = new int[aLength];
  System.arraycopy(aMatrix, 0, myInt[i], 0, aLength);
}

I don’t have a benchmark but I can bet with my 2 cents that they are faster and less mistake-prone than doing it yourself. Especially, System.arraycopy() as it is implemented in native code.

Hope this helps.

Edit: fixed bug.

It is possible to use streams in Java 8 to copy a 2D array.

@Test
public void testCopy2DArray() {
   int[][] data = {{1, 2}, {3, 4}};
   int[][] dataCopy = Arrays.stream(data)
             .map((int[] row) -> row.clone())
             .toArray((int length) -> new int[length][]);

   assertNotSame(data, dataCopy);
   assertNotSame(data[0], dataCopy[0]);
   assertNotSame(data[1], dataCopy[1]);

   dataCopy[0][1] = 5;
   assertEquals(2, data[0][1]);
   assertEquals(5, dataCopy[0][1]);
}

You are not initializing the local 2D array.

int[][] myInt = new int[matrix.length][];
for(int i = 0; i < matrix.length; i++)
{
  myInt[i] = new int[matrix[i].length];
  for (int j = 0; j < matrix[i].length; j++)
  {
    myInt[i][j] = matrix[i][j];
  }
}

If the data is large you should consider using a proper linear algebra library like colt or nd4j. System.arraycopy will likely only be meaningfully faster if the array were single dimensional. Otherwise it can not copy the entire data as one unit and then reshape it as in numpy or R.

you can code like this also
myInt = matrix.clone();

Leave a Reply

Your email address will not be published. Required fields are marked *