简体   繁体   中英

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

        }
    }

}

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 )

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 BA==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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM