Reputation: 153
Having written the code below, I was wondering why clone() doesn't return the same hashcode for each additional instance. Am I doing something wrong?
public class Accessor implements Cloneable {
public static void main(String[] args) {
Accessor one = new Accessor();
Accessor two = one.clone();
System.out.println("one hahcod " + one.hashCode()
+"\ntwo hashcode " + two.hashCode());
}
public Accessor clone(){
try{
return (Accessor)super.clone();
}
catch (CloneNotSupportedException err){
throw new Error("Error!!!");
}
}
}
Upvotes: 0
Views: 146
Reputation: 14401
The clone method creates a shallow copy of your first object but your Accessor class has no instance field and does not override hashCode method, as a consequence the instances of this class get the default behaviour from Object class for hashCode. This behaviour is similar as calling System#identityHashCode with your object as parameter.
Upvotes: 1
Reputation: 4551
Since Accessor
does not override hashCode
, you will get the default implementation of Object.hashCode
. This has implementation-defined semantics but will basically cast the address of the object to an integer, such that distinct object instances will have different hashCode
s.
See What is the default implementation of `hashCode`? for more information on the above.
Note that if you are going to implement hashCode
, you should also implement equals
. For a good reference on equals
and hashCode
, read Joshua Bloch's Effective Java (or see Best implementation for hashCode method)
Upvotes: 2
Reputation: 9492
Because it is a different object. You are invoking the cloning inherited from Object in this case. For each new object you will have a different dashcode. If you open the source code of Object in java what you will find there is the following:
public native int hashCode();
public boolean More ...equals(Object obj) {
return (this == obj);
}
The key point here is that once you clone an object A clone of B A==B will always return false.
Then if you read the hashcode documentation it states the following :
If two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two objects must produce the same integer result. It is not required that if two objects are unequal according to the equals(java.lang.Object) method, then calling the hashCode method on each of the two objects must produce distinct integer results. However, the programmer should be aware that producing distinct integer results for unequal objects may improve the performance of hashtables.
Upvotes: 1