Java 如何实现 hashCode 和 equals 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2132334/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to implement hashCode and equals method
提问by Vidya
How should I implement hashCode()
and equals()
for the following class in Java?
我应该如何实施hashCode()
和equals()
在Java下面的类?
class Emp
{
int empid ; // unique across all the departments
String name;
String dept_name ;
String code ; // unique for the department
}
采纳答案by jutky
in Eclipse right mouse click-> source -> generate hashCode() and equals() gives this:
在 Eclipse 中右键单击-> 源代码-> 生成 hashCode() 和 equals() 给出了这个:
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (code == null ? 0 : code.hashCode());
return result;
}
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (!(obj instanceof Emp))
return false;
Emp other = (Emp) obj;
return code == null ? other.code == null : code.equals(other.code);
}
I've selected code as a unique field
我已选择代码作为唯一字段
回答by sfussenegger
If code is unique (i.e. your business key), it's best to only use the code for equals and hashCode - it's good practice to seperate business key (code) from object id (id).
如果代码是唯一的(即您的业务键),最好只使用 equals 和 hashCode 的代码 - 将业务键(代码)与对象 id (id) 分开是一种很好的做法。
Here's a nice read: Hibernate Documentation: Equals and HashCode(valid not only for Hibernate itself)
这是一个不错的阅读:Hibernate 文档:Equals 和 HashCode(不仅对 Hibernate 本身有效)
回答by jeff porter
what ever values you use in equals to determine if two objects are the same, are the the values that you need to use to create a hash code.
您在 equals 中使用的值来确定两个对象是否相同,是您需要用来创建哈希码的值。
public boolean equals(Object o) {
boolean result = false;
if(o instanceof CategoryEnum) {
CategoryEnum ce = (CategoryEnum) o;
result = ce.toString().equals(name);
}
return result;
}
public int hashCode()
{
int hash = 6;
hash += 32 * name.hashCode();
return hash;
}
回答by user258444
equals()and hashcode(),They have a lot of different places. equals(),if we don't Override it from Object,it represent that whether two variables are pointing to the same object heap?
equals()和hashcode(),它们有很多不同的地方。equals(),如果我们不从Object覆盖它,它代表两个变量是否指向同一个对象堆?
public Class Student(){
private int id;
private name;
public Student(int id,String name){
this.name=name;
this.id=id;
}
public void main(String[] args){
Student A=new Student(20,'Lily');
Student B=new Student(20,'Lily');
boolean flag=A.equals(B)//flag=flase;
/*
*Although they attribute the same, but they are two different objects, they point to different memory
*/
@Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (this == obj) {
return true;
}
if (this.getClass() != obj.getClass()) {
return false;
}
Student s=(Student)obj;
return new Integer(this.id).equals(new Integer(s.id))&&this.name.equals(s.name);
}
/**
*Sometimes even though we Override the equals, but we still can not determine whether the *two objects the same,
*In the collection object, such as HashSet, this time we have to Override the hashoCode ()
*/
public int hashCode(){
return id + name.hashCode() ;
}
回答by user2068018
try this code, use org.apache.commons.lang3.builder
试试这个代码,使用 org.apache.commons.lang3.builder
public int hashCode() {
return new HashCodeBuilder(17, 31). // two randomly chosen prime numbers
append(empid).
append(name).
append(dept_name ).
append(code ).
toHashCode();
}
public boolean equals(Object obj) {
if (obj == this)
return true;
if (!(obj instanceof Person))
return false;
Emp rhs = (Emp) obj;
return new EqualsBuilder().
// if deriving: appendSuper(super.equals(obj)).
append(name, rhs.name).
isEquals();
}
回答by Vituel
Guava has helper methods for creating them. You tell it which fields to take in consideration and it will handle nulls for you and do the prime number calculation for hashcode.
Guava 有创建它们的辅助方法。您告诉它要考虑哪些字段,它会为您处理空值并为哈希码计算质数。
IDEs can also generate them based on the fields you choose.
IDE 还可以根据您选择的字段生成它们。
The advantage of delegating it to a tool like that is you get a standard solution and will worry less about bugs and maintenance of varied implementations spread all over your project.
将其委托给这样的工具的好处是您可以获得一个标准的解决方案,并且可以减少对遍布整个项目的各种实现的错误和维护的担忧。
Here's an example of using Guava and generated by an IntelliJ plugin: https://plugins.jetbrains.com/plugin/7244?pr=
这是使用 Guava 并由 IntelliJ 插件生成的示例:https://plugins.jetbrains.com/plugin/7244 ?pr =