在Java中,我应该如何实现以下类的hashCode()
和equals()
方法?
class Emp
{
int empid ; // unique across all the departments
String name;
String dept_name ;
String code ; // unique for the department
}
在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);
}
我已将代码选择为唯一字段
Emp
具有相同的代码,它们是相等的吗?在这种实现中,您至少需要添加 dept_name
。 - Pascal Thivent尝试使用这段代码,使用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();
}
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;
}
public int hashCode() {return 42;}
)——这会破坏散列集合(HashMap、HashSet等)的性能,但它们仍然能够正常工作。因此,这比一个无效的hashCode方法要好。唯一的规则是:如果两个对象相等(a.equals(b)
),则它们必须具有相同的哈希码(a.hashCode() == b.hashCode()
)。如果它们不相等,则哈希码仍可能相等。 - sfusseneggerequals()和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() ;
}
string
的类?你真的应该看一下这个:http://java.sun.com/docs/codeconv/html/CodeConvTOC.doc.html - Bart Kiersequals()
和hashCode()
。您需要做的就是选择它应该依赖的字段。 - Jiri Kremserequals
方法的处理方式。 - Paul Rooney