我有一個POJO,在我所定義的hashCode方法我認爲是的..正確實現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;
公共類Employee {
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;
}
} 這裏
嗨,所以請你告訴我我的hashcode()實現有什麼問題。!1 – Neera 2012-04-15 18:06:35
你的版本比Eclipse的版本產生更多(錯誤)散列衝突。 – 2012-04-15 18:13:17
@ user1334074:查看我的更新。基本上希望'hashCode()'應該爲稍微不同的對象返回不同的結果。 – 2012-04-15 18:16:15