如何实现hashCode和equals方法
我应该如何在Java中为以下类实现hashCode()
和equals()
?
class Emp { int empid ; // unique across all the departments String name; String dept_name ; String code ; // unique for the department }
在Eclipse中右键单击 – > source – > generate 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); }
我选择了代码作为一个独特的领域
试试这段代码,使用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(); }
Guava有辅助方法来创建它们。 你告诉它要考虑哪些字段,它将为你处理空值并进行哈希码的素数计算。
IDE还可以根据您选择的字段生成它们。
将它委托给这样一个工具的好处是你可以得到一个标准的解决方案,并且不用担心错误和维护各种各样的实现,这些实现遍布整个项目。
这是一个使用Guava并由IntelliJ插件生成的示例: https ://plugins.jetbrains.com/plugin/7244 ? pr =
如果代码是唯一的(即您的业务密钥),最好只使用equals和hashCode的代码 – 从对象id(id)中分离业务密钥(代码)是一种好的做法。
这是一个很好的阅读: Hibernate文档:Equals和HashCode (不仅适用于Hibernate本身)
您在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; }
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() ; }