The output of the following codeblock is 'false'. Why?
byte[] a = {1,2,3};
byte[] b = (byte[]) a.clone();
System.out.print(a==b);
The output of the following codeblock is 'false'. Why?
byte[] a = {1,2,3};
byte[] b = (byte[]) a.clone();
System.out.print(a==b);
array does not override equals method . So it will go for reference equality check which is false in this case
==
is the identity operator in Java. It means, it checks if two objects are the same thing. It's not about logical equality, it's not about containing the same values. It's about being the same object.
In your example, they are not the same object. The clone method of an array creates a new object, with the same content as the original. The new object will have the same content, but it will have its own identity. It's a new object, distinct from the original.
In contrast, the equals method is about logical equality. That is, two objects containing equal values. When cloning an array, the original and the clone are equal, because they have the same values. But they are not identical, because they have different identities. In terms of Java's ==
operator and the contract of equals
method:
The importance of identity is that when two array variables have the same identity (both pointing to the same object), then modifying one of them will appear to modify both of them. When two arrays are equal but not identical, you can modify one without affecting the other: they are completely independent objects.
Because a and b are not referencing to the same object. When you use clone() function, a new reference object is created in java.
In your out put you are comparing two instances of different objects which are not the same. Think of this as the location in memory where the object is stored. So the false
printout is not due to the clone, but the comparison.
Cloaning means you create a copy of the object that has the same values. What exactly that means is not defined: a clone is usually not a deep clone so cloning an object A
-> B
referencing Object c
, then usually c
will be referenced from both A
and B
.
A good reference is the Javadoc and Joshua Bloch's Effective Java Item 11:'Override clone judiciously'
byte[] a = {1,2,3};
byte[] b = a.clone();
boolean isEqual = Arrays.equals(a, b);
System.out.print(isEqual);
For details about clone : http://www.javatpoint.com/object-cloning
Think you would might be trying to compare the elms inside the arrays.
for(int i = 0; i<a.length; i++)
{ System.out.println(a[i] == b[i]);}