Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I copy a 2 Dimensional array in Java?

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

like image 742
badcoder Avatar asked Apr 11 '11 05:04

badcoder


People also ask

Can you copy arrays in Java?

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.

How do you create a copy of an array in Java?

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.


2 Answers

Since Java 8, using the streams API:

int[][] copy = Arrays.stream(matrix).map(int[]::clone).toArray(int[][]::new); 
like image 142
Gayan Weerakutti Avatar answered Oct 05 '22 18:10

Gayan Weerakutti


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

like image 33
Louis Rhys Avatar answered Oct 05 '22 18:10

Louis Rhys