简体   繁体   中英

Can I use hashcode of class member for class?

I have class with final String as unique ID. Of course I want to override equals so comparison is based on ID only. Is it correct practice then to just return hash code of ID, like below?

class ItemSpec{
    final String name;

    ...

    @Override
    public boolean equals(Object o){
        if(o != null && o instanceof ItemSpec){
            return name.equalsIgnoreCase(((ItemSpec)o).name);
        } else{
            return false;
        }
    }

    @Override
    public int hashCode(){
         if(name == null){
             return 0;
         } else{
             return name.hashCode();
         }
    }
}

Not if your equals is case insensitive. You could have two ItemSpec coming out as equal but with different hash codes. That breaks the most crucial requirement of a hash code.

Your equals has to agree with your hashCode . So if you are going to compare them case insensitively, you have to write your hashCode case insensitively.

@Override
public int hashCode(){
     if (name == null){
         return 0;
     } else{
         return name.toLowerCase().hashCode();
     }
}

Also your hashCode method implies that name could be null. If so, you should null-check it in your equals method as well.

I dont see any problem with your approach.

But, I've often seen the following implementation:

public int hashCode() {
    final int prime = 31;
    int result = super.hashCode();
    result = prime * result + ((name == null) ? 0 : name.hashCode());
    return result;
}

Update: Here is a link with a better explanation: Best implementation for hashCode method

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