私は、2つの文字列に依存するマップキーとして使用されるFeatureEntryKeyを必要とします。私はデフォルトで文字列値が平等をうまく扱えることを覚えているので、ここで2つのメソッドを自動生成する必要はありません。本当?hashCodeとequalsメソッドを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