问题
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();
}
}
}
回答1:
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.
回答2:
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
来源:https://stackoverflow.com/questions/25936945/can-i-use-hashcode-of-class-member-for-class