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; }
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.
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]); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With