tags:

views:

85

answers:

3

Hi guys - 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;
}
+2  A: 

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];
  }
}
Amarghosh
+3  A: 

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

Here is how to use close 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, aLength, myInt, 0);
}

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.

NawaMan
Arrays.copyOf() also can be used
Pete Kirkham
Pete is right. But Arrays.copyOf() makes use of System.arraycopy() with an over head for the assumption that the length of the result might not be the same as the original. In this case we know for sure the size of the result, so it is much more efficient to use clone() and System.arraycopy() as they are native. Nonetheless, Arrays.copyOf() can be use too.
NawaMan
A: 

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

valli
That will create a matrix which shares the row arrays as the original
Pete Kirkham