sayid jetzenden sayid jetzenden - 2 months ago 16
Java Question

Java clone() inquiry

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!!!");

}
}

}

Answer

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 hashCodes.

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)

Comments