copy a 2d array in java

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.

Leave a Comment