The copy of the array is divided into 2 cases, a shallow copy, a reference pass, and a deep copy, which is not simply a copy of the reference, but also opens up a new memory space
A) shallow copy is available in three ways:
The first way to take advantage of a For loop: int[] a={1,2,4,6};int length=a.length;int[] b=new int[length];for (int i = 0; i < length; i++) {B[i]=a[i ];} The second way is directly assigned: int[] array1={1,2,4,6};int[] array2=a;/* here to copy the value of the array1 array to array2, if you run this way, you will find that the value of the two array is the same at this time. This is passing a reference (that is, an address), and then changing one of the arrays and the other will change as well. *////Third Way: using Arrays copyOf int copy[] = arrays.copyof (A, a.length);
II) deep copy of one-dimensional array (system.arraycopy ())
/**
* There are several methods for deep-copy arrays:
* 1. Call Clone
* 2. Call System.arraycopy
* Both of these are equivalent to the basic type and object type data.
* 3. Use a For loop to copy each element of the array. (Note that the Clone method is called)
*/
Example:
Object[] src = new Object[]{ new String ("Zhao"), integer.valueof (1), integer.valueof (2), integer.valueof (3), integer.valueof (4)}; object[] dest = src.clone (); &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;&NBSP;//1. Copy Data // Object[] dest = new object[5]; // system.arraycopy (src, 0 , dest, 0, dest.length); system.out.println ( dest.equals (SRC)); System.out.println (&NBsp;dest == src ); for (int i = 0; i < dest.length; i++) { system.out.print ( dest[i]+ ", " ); dest[i] = new string ("KE"); //2. Changing the contents of a new array system.out.print ( dest[i]+ ", " ); System.out.println ( src[i]+ ","); //3. does not affect the original array } system.out.println ();
Note: Deep copies under one-dimensional arrays are only shallow copies in multidimensional arrays!!
Java Array Copy