First, let's look at the following two procedures:
(1 ).
1 int [] a = {1, 2, 3, 4}; 2 int [] B = new int [4]; 3 B =;(2 ).
1 int [] a = {1, 2, 3, 4}; 2 int [] B = new int [4]; 3 int I = 0; 4 for (int num: a) {5 B [I ++] = num; 6}After the value is assigned, all values of array B are
{1, 2, 3, 4}But there is a substantial difference between the two methods. First, the array initialization process is as follows:
Int [];First define an array name
A, And then
AThis variable is added to the stack. Of course there is no
AInitialization, so
AIs an empty reference. For
Int [] a = {1, 2, 3, 4}First, define a variable.
AAnd set
AStack, and create an object in the heap area.
{1, 2, 3, 4}, And finally create
AObject
{1, 2, 3, 4}. Second, value transfer and reference transfer, the first method is actually changed
AReferences,
A,
BReferencing the same object also produces a negative consequence,
BThe referenced object is no longer referenced, and a piece of memory garbage is generated. As shown in: the second method is
BThe value of the referenced memory region is not changed.
B. Do not use the reference transfer method to copy an array. This will not only generate memory garbage, but will also change the original array if not appropriate.