How do I copy a 2 Dimensional array in Java?

JavaArraysMultidimensional ArrayCopy

Java Problem Overview


I need to make a copy of a fairly large 2 dimensional array for a project I am working on. I have two 2D arrays:

int[][]current;
int[][]old;

I also have two methods to do the copying. I need to copy the array because current is regularly being updated.

public void old(){
  old=current
}

and

public void keepold(){
  current=old
}

However, this does not work. If I were to call old, make an update on current, and then call keepold, current is not equal to what it was originally. Why would this be?

Thanks

Java Solutions


Solution 1 - Java

Since Java 8, using the streams API:

int[][] copy = Arrays.stream(matrix).map(int[]::clone).toArray(int[][]::new);

Solution 2 - Java

current=old or old=current makes the two array refer to the same thing, so if you subsequently modify current, old will be modified too. To copy the content of an array to another array, use the for loop

for(int i=0; i<old.length; i++)
  for(int j=0; j<old[i].length; j++)
    old[i][j]=current[i][j];

PS: For a one-dimensional array, you can avoid creating your own for loop by using Arrays.copyOf

Solution 3 - Java

> /** > * Clones the provided array > * > * @param src > * @return a new clone of the provided array > */ > public static int[][] cloneArray(int[][] src) { > int length = src.length; > int[][] target = new int[length][src[0].length]; > for (int i = 0; i < length; i++) { > System.arraycopy(src[i], 0, target[i], 0, src[i].length); > } > return target; > }

Is it possible to modify this code to support n-dimensional arrays of Objects?

You would need to support arbitrary lengths of arrays and check if the src and destination have the same dimensions, and you would also need to copy each element of each array recursively, in case the Object was also an array.

It's been a while since I posted this, but I found a nice example of one way to create an n-dimensional array class. The class takes zero or more integers in the constructor, specifying the respective size of each dimension. The class uses an underlying flat array Object[] and calculates the index of each element using the dimensions and an array of multipliers. (This is how arrays are done in the C programming language.)

Copying an instance of NDimensionalArray would be as easy as copying any other 2D array, though you need to assert that each NDimensionalArray object has equal dimensions. This is probably the easiest way to do it, since there is no recursion, and this makes representation and access much simpler.

Solution 4 - Java

I solved it writing a simple function to copy multidimensional int arrays using System.arraycopy

public static void arrayCopy(int[][] aSource, int[][] aDestination) {
    for (int i = 0; i < aSource.length; i++) {
        System.arraycopy(aSource[i], 0, aDestination[i], 0, aSource[i].length);
    }
}

or actually I improved it for for my use case:

/**
 * Clones the provided array
 * 
 * @param src
 * @return a new clone of the provided array
 */
public static int[][] cloneArray(int[][] src) {
    int length = src.length;
    int[][] target = new int[length][src[0].length];
    for (int i = 0; i < length; i++) {
        System.arraycopy(src[i], 0, target[i], 0, src[i].length);
    }
    return target;
}

Solution 5 - Java

You can also do as follows:

public static int[][] copy(int[][] src) {
	int[][] dst = new int[src.length][];
	for (int i = 0; i < src.length; i++) {
		dst[i] = Arrays.copyOf(src[i], src[i].length);
	}
	return dst;
}

Solution 6 - Java

Using java 8 this can be done with

int[][] destination=Arrays.stream(source)
                    .map(a ->  Arrays.copyOf(a, a.length))
                    .toArray(int[][]::new);

Solution 7 - Java

Arrays in java are objects, and all objects are passed by reference. In order to really "copy" an array, instead of creating another name for an array, you have to go and create a new array and copy over all the values. Note that System.arrayCopy will copy 1-dimensional arrays fully, but NOT 2-dimensional arrays. The reason is that a 2D array is in fact a 1D array of 1D arrays, and arrayCopy copies over pointers to the same internal 1D arrays.

Solution 8 - Java

current = old ;

Assignment operations doesnot copy elements of one array to another. You are just making the current matrix refer to the old matrix. You need to do a member wise copy.

Solution 9 - Java

I am using this function:

public static int[][] copy(final int[][] array) {
    if (array != null) {
        final int[][] copy = new int[array.length][];

        for (int i = 0; i < array.length; i++) {
            final int[] row = array[i];

            copy[i] = new int[row.length];
            System.arraycopy(row, 0, copy[i], 0, row.length);
        }

        return copy;
    }

    return null;
}

The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:

final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };

Solution 10 - Java

Here's how you can do it by using loops.

public static int[][] makeCopy(int[][] array){
    b=new int[array.length][];
    
    for(int row=0; row<array.length; ++row){
        b[row]=new int[array[row].length];
        for(int col=0; col<b[row].length; ++col){
            b[row][col]=array[row][col];
        }
    }
    return b;
}

Solution 11 - Java

you could also use a for each loop

int r=0;
for(int[] array:old){
    int c=0;
    for(int element:array)
        current[r][c++]=array;
    r++;
}

Or

int c=0;
for(int array[]:old){
    System.arraycopy(array,0,current[c++],0,array.length);
}

However something like:

int c=0;
for(int[] array:old){
    current[c++]=array;
}

would be wrong as it would just copy references of the subarrays of old and changes made to old would be reflected in current.

Solution 12 - Java

public  static byte[][] arrayCopy(byte[][] arr){
	if(arr!=null){
		int[][] arrCopy = new int[arr.length][] ;
		System.arraycopy(arr, 0, arrCopy, 0, arr.length);
		return arrCopy;
	}else { return new int[][]{};}
}

Solution 13 - Java

You can give below code a try,

public void multiArrayCopy(int[][] source,int[][] destination){
destination=source.clone();}

Hope it works.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionbadcoderView Question on Stackoverflow
Solution 1 - JavaGayan WeerakuttiView Answer on Stackoverflow
Solution 2 - JavaLouis RhysView Answer on Stackoverflow
Solution 3 - Javambomb007View Answer on Stackoverflow
Solution 4 - JavaDaniel BackmanView Answer on Stackoverflow
Solution 5 - JavaJohnny LimView Answer on Stackoverflow
Solution 6 - JavaRakesh ChauhanView Answer on Stackoverflow
Solution 7 - JavaSajidView Answer on Stackoverflow
Solution 8 - JavaMaheshView Answer on Stackoverflow
Solution 9 - JavaNiklasView Answer on Stackoverflow
Solution 10 - JavaArafe Zawad SajidView Answer on Stackoverflow
Solution 11 - JavaOmnicacorpView Answer on Stackoverflow
Solution 12 - JavaSatishView Answer on Stackoverflow
Solution 13 - JavaAdil BhattyView Answer on Stackoverflow