Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

copy a 2d array in java

Tags:

java

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; } 
like image 767
roberto duran Avatar asked Nov 06 '09 09:11

roberto duran


People also ask

How do I copy a 2D array to another?

Copying Arrays Using arraycopy() method src - source array you want to copy. srcPos - starting position (index) in the source array. dest - destination array where elements will be copied from the source. destPos - starting position (index) in the destination array.


2 Answers

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.

like image 101
7 revs, 7 users 65% Avatar answered Sep 23 '22 02:09

7 revs, 7 users 65%


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]); } 
like image 45
NickF Avatar answered Sep 22 '22 02:09

NickF