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 allows you to copy arrays using either direct copy method provided by java. util or System class. It also provides a clone method that is used to clone an entire array.
If you want to copy the first few elements of an array or a full copy of an array, you can use Arrays. copyOf() method. Arrays. copyOfRange() is used to copy a specified range of an array.
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
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