Java Reference
In-Depth Information
Recall, in Chapter 6, that we were not able to implement a method for swapping two integers using method's
parameters of primitive types. It was so, because, for primitive types, the actual parameters are copied to the
formal parameter. Here, we were able to swap two integers inside the swap() method, because we used an array as
the parameter. The array's reference is passed to the method, not the copy of the elements of the array.
There is a risk when an array is passed to a method. The method may modify the array elements, which,
sometimes, may not be desired or intended. In such a case, you should pass a copy of the array to the method, not the
original array. If the method modifies the array, your original array is not affected.
You can make a quick copy of your array using array's clone() method. The phrase “quick copy” warrants special
attention. For primitive types, the cloned array will have a true copy of the original array. A new array of the same
length is created and the value of each element in the original array is copied to the corresponding element of the
cloned array. However, for reference types, the reference of the object stored in each element of the original array is
copied to the corresponding element of the cloned array. This is known as a shallow copy, whereas the former type,
where the object (or the value) is copied, is known as a deep copy. In case of a shallow copy, elements of both arrays,
the original and the cloned, refer to the same object in memory. You can modify the objects using their references
stored in the original array as well as the cloned array. In this case, even if you pass a copy of the original array to a
method, your original array can be modified inside the method. The solution to this problem is to make a deep copy
of your original array to pass it to the method. The following snippet of code illustrates the cloning of an int array and
a String array. Note that the return type of the clone() method is Object and you need to cast the returned value to
an appropriate array type.
// Create an array of 3 integers 1,2,3
int[] ids = {1, 2, 3};
// Declare an array of int named clonedIds.
int[] clonedIds;
// The clonedIds array has the same values as the ids array.
clonedIds = (int[])ids.clone()
// Create an array of 3 strings.
String[] names = {"Lisa", "Pat", "Kathy"};
// Declare an array of String named clonedNames.
String[] clonedNames;
// The clonedNames array has the reference of the same three strings as the names array.
clonedNames = (String[])names.clone();
The cloning process for primitive array ids and reference array names in the above snippet of code is depicted in
Figure 15-2 through Figure 15-5 .
 
Search WWH ::




Custom Search