具有多个equals和if的Java哈希代码实现
据我所知,每个equals对象都必须有相同的哈希代码。然而,如果在equals方法中有多个,如果需要遵循,该怎么办 位置是对象,连接是对象,长度是整数,偏移是整数,截面是对象 我已经解决了一个atAJunction方法,我只使用junction作为附加的哈希代码。当截面相等时,其截面长度等于两个位置的偏移量。我在这里使用的hashcode只使用section作为hashcode 主要问题是,它们具有不同的截面,但偏移量和端点相同。它相等,但哈希代码不同 有人能帮我解决问题吗?谢谢。:) 这是我的方法:具有多个equals和if的Java哈希代码实现,java,hash,equals,hashcode,hash-collision,Java,Hash,Equals,Hashcode,Hash Collision,据我所知,每个equals对象都必须有相同的哈希代码。然而,如果在equals方法中有多个,如果需要遵循,该怎么办 位置是对象,连接是对象,长度是整数,偏移是整数,截面是对象 我已经解决了一个atAJunction方法,我只使用junction作为附加的哈希代码。当截面相等时,其截面长度等于两个位置的偏移量。我在这里使用的hashcode只使用section作为hashcode 主要问题是,它们具有不同的截面,但偏移量和端点相同。它相等,但哈希代码不同 有人能帮我解决问题吗?谢谢。:) 这是我的
@Override
public boolean equals(Object object) {
if(object == null){
return false;
}
if(!(object instanceof Location)){
return false;
}else{
Location otherLocation = (Location) object;
if(atAJunction() && otherLocation.atAJunction()){
return this.endPoint.getJunction().equals(otherLocation.getEndPoint().getJunction());
}else{
// The Problem Here
if(this.endPoint.equals(otherLocation.endPoint)){
return this.offset == otherLocation.getOffset();
}else{
return this.section.equals(otherLocation.getSection()) &&
this.section.getLength() == (this.offset + otherLocation.getOffset());
}
}
}
}
这是我的哈希代码:
@Override
public int hashCode() {
// creates a polynomial hash-code based on the fields of the class.
final int prime = 13; // an odd base prime
int result = 1; // the hash code under construction
if(atAJunction()){
result = prime * result + this.endPoint.getJunction().hashCode();
}else{
result = prime * result + this.section.hashCode();
}
return result;
}
请填写下面的例子
public class Point {
private final int x;
private final int y;
public Point(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
// ...
}
然后像在有效的Java中一样创建Equals和HashCode
// A better definition, but still not perfect
@Override public boolean equals(Object other) {
boolean result = false;
if (other instanceof Point) {
Point that = (Point) other;
result = (this.getX() == that.getX() && this.getY() == that.getY());
}
return result;
}
@Override public int hashCode() {
return (41 * (41 + getX()) + getY());
}
首先,我不明白的是你为什么需要这张额外的支票
return this.section.equals(otherLocation.getSection()) &&
**this.section.getLength() == (this.offset + otherLocation.getOffset());**
理想情况下,如果截面相等,那么长度和所有部分都应该包含在其中。比较一个对象的内部值和另一个类的某些派生值容易出错,在equals()之类的方法中应该避免
你可能想看看这本书。作者在这里解释了哈希代码和equals之间的关系。这对你肯定有帮助
在您的情况下,我的建议是,如果您不太清楚生成hashcode()和equals()的正确方法,请尝试使用IDE中内置的codegenerators,如Eclipse或netbeans。您确定equals方法正确吗?记住等式必须是自反的:如果a.equals(b)和b.equals(c)那么a.equals(c)-我不明白你如何保证这一点作为旁注,当if语句只包含return语句时,不要使用“else”后来,因为它是多余的,并增加了很多混乱的代码在该网站上你可以找到所有的解释。似乎你改变了整个帖子只包含代码。我建议你也做一些解释。谢谢你的回答。首先,我使用附加检查是因为要求我这样做。要求位置相等的一个条件是:截面的长度必须与位置偏移量+其他位置的偏移量(要比较的另一个对象)的总和相同,但在这种情况下,this.offset+其他位置.getOffset());以及这个.section.hashCode();它们相互矛盾。hashcode没有考虑这个问题。offset+otherLocation.getOffset());,由相等者使用。