gpt4 book ai didi

java - hashcode() 的正确实现

转载 作者:行者123 更新时间:2023-12-01 16:34:57 25 4
gpt4 key购买 nike

我有一个 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;

公共(public)类员工{

 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() 更加敏感。例如。如果你互相交换 jobname 值,你的 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

另请参阅

关于java - hashcode() 的正确实现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10164546/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com