Java Reference
In-Depth Information
a = 1000
b = 2000
location 2000:
location 1000:
2
234
14
12
23
2
FIGURE 5.3: Example of shallow copy.
Shallow copy is when you copy the address of an array, but not the array itself. The
result is having two variables that point to the same array. Any change to the array
using one of the variables will affect the other variables. This behavior is undesirable
and shallow copying should be avoided.
Next, let us fix the program and make sure that changes to the b array do not affect the
a array. Below is a possible solution.
public class Test
{
public static void main(String [] args)
{
int a[] = new i n t []
{
2,234,14,12,23,2
}
;
int b[] = new i n t [6];
for ( int i= 0;
i < a . l e n g t h ;
i ++) {
b[i] =a[i];
b[3]=7;
System. out . println (a [ 3 ] ) ;
}
}
Now, as expected, the final value of a[3] will be 12. The only way to make a and b
independent arrays, where modifying an element in one of the arrays does not affect the
other array, is to use a for loop. The loop copies all the elements from the a array to the b
array one by one. After the for loop executes, the value of a is still 1000 and the value of b
is still 2000. In other words, the for loop does not change the value of b . It simply copies
the elements from a to b one by one. This type of array copying is known as deep copy .
Deep copy of arrays is when the elements of the array are copied one by one. This
type of copying is preferred to shallow copy because the two arrays will be independent
and modifying an element in one of the arrays will not affect the other array.
Since deep copy is such a common operation, Java supports the Arrays.copyOf method,
which performs a deep copy of an array. Here is an example of how the method can be used.
public class Test
{

Search WWH ::

Custom Search