我想要FeatureEntryKey用作Map Key,它依賴於兩個字符串。我記得默認情況下,字符串值可以很好地處理平等,所以不需要在這裏自動生成這兩種方法。真的嗎?我是否需要重寫hashCode並使用compareTo方法等於方法?
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;
}
}
那究竟是什麼問題? – Mureinik
類別。如果實現'CompareTo',但不覆蓋'equals',則最終可能會出現'a.compareTo(b)== 0'但是'a.equals(b)== false'的情況。這顯然令人困惑。和往常一樣,如果你重寫'equals',你應該重載'hashCode'。 – Michael