How do I copy a 2 Dimensional array in 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
how to copy a multidimensional array to a single array?
Here is the correct way to use the arraycopy:
int copy[] = new int[arr[r].length];
System.arraycopy(arr[r], 0, copy, 0, copy.length);
return copy;
A shorter way of writing the above:
return Arrays.copyOf(arr[r], arr[r].length);
A third way:
return arr[r].clone();
All three ways will have the same result. As for speed, the first two ways may be a tiny bit faster than the third way.
Cloning two-dimensional Arrays in Java
you should iterate this array with two loops. This will helps you:
static double[][] clone(double[][] a) {
double[][] b = new double[a.length][];
for (int i = 0; i < a.length; i++) {
b[i]= new double[a[i].length];
for (int j = 0; j < a[i].length; j++)
b[i][j] = a[i][j];
}
return b;
}
Java: copy a single array from a 2d array
If you want a reference to a row, you can use double[] selectedRow = P[rowToSelect]
. The new
keyword in your code is misplaced. If you want a real copy or better known as deep copy, you can use:
double[] selectedRow = new double[P[rowToSelect].length];
System.arraycopy(P[rowToSelect], 0, selectedRow, 0, P[rowToSelect].length);`
How do I do a deep copy of a 2d array in Java?
Yes, you should iterate over 2D boolean array in order to deep copy it. Also look at java.util.Arrays#copyOf
methods if you are on Java 6.
I would suggest the next code for Java 6:
public static boolean[][] deepCopy(boolean[][] original) {
if (original == null) {
return null;
}
final boolean[][] result = new boolean[original.length][];
for (int i = 0; i < original.length; i++) {
result[i] = Arrays.copyOf(original[i], original[i].length);
// For Java versions prior to Java 6 use the next:
// System.arraycopy(original[i], 0, result[i], 0, original[i].length);
}
return result;
}
Related Topics
How to Call JavaScript from Android
Android M Permissions: Onrequestpermissionsresult() Not Being Called
Android Service Needs to Run Always (Never Pause or Stop)
Android Adding Simple Animations While Setvisibility(View.Gone)
Java Program That Runs Commands with Linux Terminal
Does Python Have an Equivalent to Java Class.Forname()
Do Interfaces Inherit from Object Class in Java
What Operations in Java Are Considered Atomic
Cannot Issue Data Manipulation Statements with Executequery()
How to Activate Jmx on My Jvm for Access with Jconsole
Number of Days in Particular Month of Particular Year
How to Understand Happens-Before Consistent
Junit Testing with Simulated User Input
How to Add and Remove Elements of Enumeration at Runtime in Java