[英]correct implementation of hashcode()
我有一個pojo,其中我自己定義了hashcode方法。
public int hashCode()
{
return name.hashCode()+job.hashCode()+salary;
}
但是由於我使用的是eclipse IDE,所以它也提供了我自動生成的哈希碼,即..
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((job == null) ? 0 : job.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + salary;
return result;
}
現在我的疑問是兩者之間的區別是什么,一種實現更好。 我完整的pojo是...
enter codepackage CollectionsPrac;
公共類員工{
String name,job;
int salary;
public Employee(String n , String j, int t )
{
this.name= n;
this.job=j;
this.salary= t;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((job == null) ? 0 : job.hashCode());
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + salary;
return result;
}
/*@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Employee other = (Employee) obj;
if (job == null) {
if (other.job != null)
return false;
} else if (!job.equals(other.job))
return false;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (salary != other.salary)
return false;
return true;
}
*/
/* @Override
public int hashCode()
{
return name.hashCode()+job.hashCode()+salary;
}*/
@Override
public boolean equals(Object obj) {
if (this == obj)
{
return true;
}
// make sure o can be cast to this class
if (obj == null || obj.getClass() != getClass())
{
// cannot cast
return false;
}
Employee e = (Employee) obj;
return this.name.equals(e.name)&&this.job.equals(e.job)&&this.salary==e.salary;
}
@Override
public String toString() {
return name+"\t" +"\t"+ job +"\t"+ salary;
}
} 這里
當涉及到POJO中的細微變化時,Eclipse生成的hashCode()
更加敏感。 例如,如果您彼此切換job
和name
值,則您的hashCode()
將返回相同的值(加法是可交換的),而精美的Eclipse版本將返回完全不同的值:
System.out.println(new Employee("John", "Blacksmith", 100).hashCode());
System.out.println(new Employee("Blacksmith", "John", 100).hashCode());
//your version of hashCode() produces identical result:
376076563
376076563
//Eclipse version:
-1520263300
926019626
最重要的區別是,如果job
或name
為null
,則您的實現將拋出NullPointerException
。
此外,eclipse生成的方法導致哈希碼更不規則,這在理論上意味着哈希表退化的可能性較低,但性能較差,但實際上這無關緊要,因為java.util.HashMap
使用輔助哈希函數在使用哈希碼之前對其進行加擾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.