Search
Close this search box.

Arrays: Copy vs. Clone

Occasionally when working with an array is may be useful to make a copy of that array. What might not be apparent is that by making a copy of an an array there are implications that can cause unintended side-effects if one isn’t aware of what actually happens when a simple copy the array is made.

For instance let’s consider:

         int [] numbers = { 2, 3, 4, 5};

         int [] numbersCopy = numbers;

The “numbersCopy” array now contains the same values, but more importantly the array object itself points to the same object reference as the “numbers” array.

So if I were to do something like:

          numbersCopy[2] = 0;

 What would be the output for the following statements?

          System.out.println(numbers[2]);

          System.out.println(numbersCopy[2]);

Considering both arrays point to the same reference we would get:

0

0

for an output.

But what if we want to make a distinct copy of the first array with its own reference? Well in that case we would want to clone the array. In doing so each array will now have its own object reference. Let’s see how that will work.

          int [] numbers = { 2, 3, 4, 5};

          int [] numbersClone = (int[])numbers.clone();

The “numbersClone” array now contains the same values, but in this case the array object itself points a different reference than the “numbers” array.

So if I were to do something like:

          numbersClone[2] = 0;

What would be the output now for the following statements?

          System.out.println(numbers[2]);

          System.out.println(numbersClone[2]);

You guessed it:

4

0

I spent some time going over this with my class but was not satisfied that we nailed this concept down very well, so I created a simple application using J# (that my student can eventually build) that I think may help illustrate this point further. It dives a little deeper into the basic mechanics of the Java Code with respect to copying or cloning arrays. So here it is. Give a try and see if it helps you draw conclusions about this topic.

I started with a simple Windows application as I did in my previous post. This example uses Strings but you could have also coded it for other types.

The idea is to compare the hash code that is generated for each array object, and compare those values.  If the hash code values are the same then we can say that the two arrays point to the same object reference.  What is interesting about this program is what it illustrates when you continue to click the “Clone Array” button and then the “Hash Code” button that corresponds to it. Compare that with what happens when you make copies of the array, and check the hash code. You can download the whole program here.

This article is part of the GWB Archives. Original Author: Daniel Forhan

Related Posts