具有多个equals和if的Java哈希代码实现

时间:2016-04-07 08:59:44

标签: java hash equals hashcode hash-collision

据我所知,每个equals对象必须具有相同的哈希码。但是,如果在equals方法中有多个,如果需要遵循该怎么办?

位置是一个对象,Junction是一个对象,length是一个整数,offset是一个整数,section是一个对象。

我已经解决了atAJunction方法时的问题,哈希码我只使用了结点作为附加的哈希码。当Section相等时,其截面长度等于两个位置的偏移量。我用于此的哈希码仅使用section作为哈希码。

主要问题是当他们有不同的部分,但相同的偏移和endPoint。它相等但哈希码不同。

有没有人能帮我解决问题?谢谢之前。 :)

这是我的Equals方法:

@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;
}

2 个答案:

答案 0 :(得分:0)

首先,我不明白为什么你需要这个额外的检查

 return this.section.equals(otherLocation.getSection()) && 
                    **this.section.getLength() == (this.offset + otherLocation.getOffset());**

理想情况下,如果部分相等,那么长度和所有部分都应该已经覆盖了。将一个对象的内部值与其他类的某个派生值进行比较是容易出错的,应该在equals()等方法中避免使用。

您可能需要查看本书http://www.amazon.com/Effective-Java-Edition-Joshua-Bloch/dp/0321356683。这里的作者以正确的方式解释了哈希码和等于的关系。这对你肯定有帮助。

在你的情况下,我建议的是,如果你不太清楚正确的方法来生成hashcode()和equals(),请尝试使用IDE中的代码生成器,如Eclipse或netbeans。

答案 1 :(得分:-1)

visit another resourse为Ex。下方。

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;
        }

        // ...
    }

比在Effective 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());
    }