我是否需要使用compareTo方法覆盖hashCode和equals方法?

时间:2017-05-22 21:21:53

标签: java hashcode comparable

我希望FeatureEntryKey用作Map键,它取决于两个字符串。我记得默认情况下String值可以很好地处理相等性,所以这里不需要自动生成这两个方法。真的吗?

public class FeatureEntryKey implements Comparable<FeatureEntryKey> {

    private String my_key;
    private String my_pos;

    public FeatureEntryKey(String key, String pos) {
        my_key = key;
        my_pos = pos;

    }

    String getKey() {
        return my_key;
    }

    String getPos() {
        return my_pos;
    }

    @Override
    public int compareTo(FeatureEntryKey entryKey) {
        int key = my_key.compareTo(entryKey.my_key);

        return key == 0 ? this.my_pos.compareTo(entryKey.my_pos) : key;
    }

    /*
     * (non-Javadoc)
     * 
     * @see java.lang.Object#hashCode()
     */
    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((my_key == null) ? 0 : my_key.hashCode());
        result = prime * result + ((my_pos == null) ? 0 : my_pos.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 (getClass() != obj.getClass())
            return false;
        FeatureEntryKey other = (FeatureEntryKey) obj;
        if (my_key == null) {
            if (other.my_key != null)
                return false;
        } else if (!my_key.equals(other.my_key))
            return false;
        if (my_pos == null) {
            if (other.my_pos != null)
                return false;
        } else if (!my_pos.equals(other.my_pos))
            return false;
        return true;
    }

}

1 个答案:

答案 0 :(得分:1)

没有; you don't have to,但你真的应该

  

强烈建议(虽然不要求)自然排序与equals一致。这是因为没有显式比较器的有序集(和有序映射)表现得很奇怪&#34;当它们与自然顺序与equals不一致的元素(或键)一起使用时。特别是,这样的有序集(或有序映射)违反了集合(或映射)的一般契约,它是根据等于方法定义的。

然而,这与String是否可以很好地处理平等无关。那个完全与你正在实施Comparable的事实有关;在实施equals时,您并未默认覆盖hashCodeComparable

如果你计划在一个集合中使用它,其中相等或散列是一个因素,那么你会想要覆盖它们,只是为了确保你得到的行为是你期望的行为。

相关问题