hashcode()和equals()方法

两个对象的hashcode相等并不能说明这两个对象equals,因为hashcode必然存在hash冲突,无论概率高低,因此严格意义上的equals方法不能仅使用两个对象的hashcode来判断他们是否equals。

有些时候我们需要重写hashcode和equal方法。例如我们需要将自定义类 点:point[x,y] 放入hashSet中或者判断两个点是否相同

建议采用apache工具包commons.lang3.builder.EqualsBuilder和commons.lang3.builder.HashCodeBuilder

@Override
    public boolean equals(Object o) {
        if (this == o)
            return true;
        if (!(o instanceof Point))
            return false;
        Point that = (Point) o;
        return new EqualsBuilder().append(x,that.).append(y,that.y).isEquals();
    }

    @Override
    public int hashCode() {
        return new HashCodeBuilder(17, 37).append(x).append(y).toHashCode();
    }