Copying arrays in java and copying arrays in java
Array replication is often used in programming. In java, array replication can be divided into two types: Reference replication, the other is deep replication (the last two arrays are irrelevant ).
Next we will use the test method to see in detail what is reference replication and deep replication.
Reference replication:
As its name implies, its value is referenced, and its value changes with the referenced object.
System. out. println ("reference copying ---------------------------"); int [] e = {1, 2, 3, 4, 56, 7, 8}; int [] f = e; for (int I = 0; I <f. length; I ++) {System. out. println (f [I]);} System. out. println ("Modify original one-dimensional array reference copy ---------------------------"); for (int I = 0; I <e. length; I ++) {e [I] = 1 ;}for (int I = 0; I <f. length; I ++) {System. out. println (f [I]);}
Result:
Reference and copy -----------------------------
1
2
3
4
56
7
8
Modify the original one-dimensional array reference copy -----------------------------
1
1
1
1
1
1
1
The following shows the two types of code for deep replication:
There are two methods:
One is clone () and the other is System. arraycopy ().
System. out. println ("Deep copy of one-dimensional arrays -------------------------"); int [] a = {, 8}; int [] B = (int []). clone (); for (int I = 0; I <B. length; I ++) {System. out. println (B [I]);} System. out. println ("change original one-dimensional array deep copy ---------------------------"); for (int I = 0; I <. length; I ++) {a [I] = 1 ;}for (int I = 0; I <B. length; I ++) {System. out. println (B [I]);} System. out. println ("one-dimensional array depth replication 1 ---------------------------"); int [] c = {, 8}; int [] d = new int [c. length]; System. arraycopy (c, 0, d, 0, c. length); for (int I = 0; I <d. length; I ++) {System. out. println (d [I]);} System. out. println ("modifying the original one-dimensional array for deep replication 1 ---------------------------"); for (int I = 0; I <c. length; I ++) {c [I] = 1 ;}for (int I = 0; I <d. length; I ++) {System. out. println (d [I]);}
Result:
Deep copy of one-dimensional arrays -----------------------------
1
2
3
4
56
7
8
Modify the original one-dimensional array for deep replication -----------------------------
1
2
3
4
56
7
8
One-dimensional array in-depth replication 1 -----------------------------
1
2
3
4
56
7
8
Modify the original one-dimensional array for deep replication -----------------------------
1
2
3
4
56
7
8
Is there any other method for copying arrays in java?
// This method is good.
Int [] a = {1, 3, 5, 7, 9 };
Int [] B = Arrays. copyOf (a, a. length );
For (int I = 0; I <a. length; I ++)
System. out. println (a [I] + "" + B [I]);
Is there any other method for copying arrays in java?
// This method is good.
Int [] a = {1, 3, 5, 7, 9 };
Int [] B = Arrays. copyOf (a, a. length );
For (int I = 0; I <a. length; I ++)
System. out. println (a [I] + "" + B [I]);