简体   繁体   中英

Is it bad practice to equal() class instances by just their unique instanceID?

I have a class that, on instantiation, creates a unique ID for its objects like so:

public class Foo {

    private final static AtomicInteger UNIQUE_ID = new AtomicInteger(0);
    private final int id;
    private final String name;         
    private final int hashcode;
    public Foo(String name) {
         id = UNIQUE_ID.GetAndIncrement();
         this.name = name;
         int result = 17;
         int result = 31 * result + id;
         int result = 31 * result + name.hashCode();
         hashcode = result;
    }
    public int getInstanceID() { return id; }

Now I want to implement hashCode and equals this way:

    public boolean equals(Object obj) {

        if (obj == this)
            return true;
        if (!(obj instanceof Foo))
            return false;

        Foo other = (Foo) obj;
        return other.getInstanceID == getInstanceID();
    }

    public int hashCode() { return hashcode; }
}

Is it considered bad practice if I just compare the ID of the objects diregarding any other field that might differ from one Foo istance to the other? Additionally should I still regard every field in the hashcode function or also just use the id?

Well. The contract goes like this - If two objects are equal, they must have the same hashCode . You haven't Overridden hashCode() , so you can have 2 equal objects with different hashcode which is wrong. override hashcode() to adhere to the contract, then it might just be fine .

The best practice is to implement the hashCode function in such a way so that it distributes the objects in a collection(hashtable) evenly. The objects which produce the same hashCode go to the same bucket. The job of hashCode function is to identify the bucket.

If you have a bad function which returns same value for all, then imagine the objects are all stored in one bucket. This makes the job difficult for the collection as it has to go through each object and run equals method on them till it finds the right one if available.

When you have a good hashCode function, then distinct objects are identified by distinct buckets. Therefore fewer objects in a given bucket, which means less search needed.

It is a good idea to use the properties of your object to uniquely identify it.

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