xxxxxxxxxx
// java.util.Arrays.copyOf() method is in java.util.Arrays class.
// It copies the specified array, truncating or padding with false
// (if necessary) so the copy has the specified length.
int[] src = {1,2,3,4};
int[] dst = Arrays.copyOf(src, src.length);
// clone() method.
int[] arrClone = src.clone()
xxxxxxxxxx
// Shallow copy
int[] src = {1,2,3,4,5};
int[] dst = Arrays.copyOf(src, src.length);
// Deep copy
int[] dst2 = new int[src.length];
for(int i = 0; i < src.length; i++){
dst2[i] = src[i];
}
xxxxxxxxxx
int[] src = new int[]{1,2,3,4,5};
int[] dest = new int[5];
System.arraycopy( src, 0, dest, 0, src.length );
xxxxxxxxxx
// method
public static int [] copyArray(int [] arr){
int [] copyArr = new int[arr.length];
for (int i = 0; i < copyArr.length; i++){
copyArr[i] = arr[i];
}
return copyArr;
}
// Arrays. method
int[] copyCat = Arrays.copyOf(arr, arr.length);
// System
System.arraycopy(x,0,y,0,5); // 5 is array's length
// clone
y = x.clone();
xxxxxxxxxx
// Java program to demonstrate Copying of Array
// using clone() method
// Main class
public class GFG {
// Main driver method
public static void main(String[] args)
{
// Input array a[]
int a[] = { 1, 8, 3 };
// Copying elements of a[] to b[]
int b[] = a.clone();
// Changing b[] to verify that
// b[] is different from a[]
b[0]++;
// Display message for better readability
System.out.println("Contents of a[] ");
for (int i = 0; i < a.length; i++)
System.out.print(a[i] + " ");
// Display message for better readability
System.out.println("\n\nContents of b[] ");
for (int i = 0; i < b.length; i++)
System.out.print(b[i] + " ");
}
}