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

Do I need to override also hashCode and equals methods with compareTo method?

我想要FeatureEntryKey作为Map Key,这取决于两个字符串。我记得默认情况下 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;
    }

}

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

It is strongly recommended (though not required) that natural orderings be consistent with equals. This is so because sorted sets (and sorted maps) without explicit comparators behave "strangely" when they are used with elements (or keys) whose natural ordering is inconsistent with equals. In particular, such a sorted set (or sorted map) violates the general contract for set (or map), which is defined in terms of the equals method.

不过,这与String能不能处理好平等关系不大。 与您正在实施 Comparable 的事实有关;在实施 Comparable.

时,您不会默认覆盖 equalshashCode

如果您计划在相等或散列是一个因素的集合中使用它,那么您可能想要覆盖这些,只是为了确保您获得的行为是您期望的行为。