How do I copy a 2 Dimensional array in Java?
Since Java 8, using the streams API:
int[][] copy = Arrays.stream(matrix).map(int[]::clone).toArray(int[][]::new);
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
/** * 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.