In Java, an array is an object, so it is also a type of reference.
The following sample code shows the values in an array as the values in the primitive type two arrays are the direct assignment of the object three array and the clone assignment
Example 1 base Type array Assignment
1 Public classTopcoder2 {3 Public Static voidMain (string[] args)4 {5 int[]a={2,3,4};6 int[]b=A;7System.out.print (a[0]+ "");8System.out.println (b[0]);9B[0]=0;TenSystem.out.print (a[0]+ ""); OneSystem.out.println (b[0]); A } -}
Output
2 2
0 0
Code analysis, line 6 assigns A to B, representing A and b pointing to the same object. So when b[0] changes, a[0] changes as well.
Example 2 base type array cloning assignment
1 Public classTopcoder2 {3 Public Static voidMain (string[] args)4 {5 int[]a={2,3,4};6 int[]b=A.clone ();7System.out.print (a[0]+ "");8System.out.println (b[0]);9B[0]=0;TenSystem.out.print (a[0]+ ""); OneSystem.out.println (b[0]); A } -}
Code Analysis, line 6 The clone of A is assigned to B, now has two copies of the array, a points to the original first copy, B points to the second copy. So when b[0] changes, a[0] is unaffected.
Output is:
2 2
2 0
Example 3 assignment of an array of reference types
1 class Number2 {3 Public intnum;4 }5 Public classTopcoder6 {7 Public Static voidMain (string[] args)8 {9Number[]a=NewNumber[3];Tena[0]=NewNumber (); Onea[0].num=2; Anumber[]b=A; -System.out.print (a[0].num+ ""); -System.out.println (b[0].num); theB[0].num=0; -System.out.print (a[0].num+ ""); -System.out.println (b[0].num); - } +}
Output is:
2 2
0 0
Analysis such as Example 1
Example 4 reference type array clone assignment
1 class Number2 {3 Public intnum;4 }5 Public classTopcoder6 {7 Public Static voidMain (string[] args)8 {9Number[]a=NewNumber[3];Tena[0]=NewNumber (); Onea[0].num=2; Anumber[]b=A.clone (); -System.out.print (a[0].num+ ""); -System.out.println (b[0].num); theB[0].num=0; -System.out.print (a[0].num+ ""); -System.out.println (b[0].num); - } +}
Output is:
2 2
0 0
Example 4 A of clone assignment to B,a and B points to a different array copy. But the references to the objects inside are the same, that is, a[0] and b[0] are pointing to the same object. But the location of the storage a[0],b[0] is different.
Different instances of value types and reference types in Java (ii)