Rajat Saxena
Rajat Saxena

Reputation: 3915

Java clone() shallow copy

The following code is not creating shallow copy as the Javadoc mentioned about clone() method

// Do the same with object arrays
obj O[] = new obj[5];
obj Oc[] = O.clone();

System.out.println("Identity hashcode of obj arrays");
System.out.println(System.identityHashCode(O));
System.out.println(System.identityHashCode(Oc));

// check objects equalness
if(O.equals(Oc)){
  System.out.println("Objects are equal!");
}

Output:

Identity hashcode of obj arrays
2018699554
1311053135

Where am I going wrong?

Upvotes: 1

Views: 98

Answers (3)

wero
wero

Reputation: 32980

You seem to expect that the cloned array will be equal to the original array, as determined by calling O.equals(Oc).

But since arrays don't override Object.equals (JLS 10.7) this call only tests if O == Oc. Therefore even if O.equals(Oc) does return false, this does not mean that Oc is not a shallow copy of O.

To test equality of array elements, you can use Arrays.equals(O, Oc)

Upvotes: 1

Ankur Singhal
Ankur Singhal

Reputation: 26067

The clone method will return a reference to a new array, which references the same objects as the source array

HashCode of both the arrays will not be same, these two are two different objects.

Upvotes: 0

TheLostMind
TheLostMind

Reputation: 36304

Yes, the output is as expected. The identity hashcodes of both arrays will be different because they are 2 different Objects (being pointed to by 2 different references) at the top level. So, the if.. condition fails as well.

What shallow copy means is : The container (Array, List etc) will be created but ht elements / references inside them will not be created newly, instead, the original references will be used / copied.

Upvotes: 3

Related Questions