Search code examples
javahashcodeclass-members

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();
         }
    }
}

Solution

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