最初,这个答案忽略了一个事实,即 aTreeSet
基于compareTo()
,而不是进行比较equals()
。已进行编辑以解决此问题。
您需要为您的对象正确定义equals()
,hashCode()
和。(由于它是 a而不是 a ,因此实施并不那么重要 - 但这是一种很好的做法。)compareTo()
Player
TreeSet
HashSet
hashCode()
Equals 和 hashCode 需要考虑所有的字段。Eclipse 可以为您自动生成一个看起来与此类似的内容(Source > Generate hashcode and equals)。
如果您已经有一个不使用所有字段的自然排序顺序TreeSet
,那么您可以为您的. 但是,即使您真的只想按字段的子集进行排序,也没有什么能阻止您按所有字段进行排序(不感兴趣的字段只扮演部分有趣的部分是相同的)。这里要注意的重要一点是 aTreeSet
不是通过方法确定相等性equals()
,而是通过compareTo() == 0
.
这是一个equals()的例子:
@Override
public boolean equals(Object obj)
{
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (getClass() != obj.getClass()) {
return false;
}
Player that = (Player) obj;
return this.age == that.age &&
this.height == that.height &&
this.weight == that.weight &&
this.games == that.games &&
this.runs == that.runs &&
this.dismisses == that.dismisses &&
this.given.equals(that.given) &&
this.family.equals(that.family);
}
这是哈希码:
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + this.age;
result = prime * result + this.dismisses;
result = prime * result + this.family.hashCode());
result = prime * result + this.games;
result = prime * result + this.given.hashCode());
result = prime * result + this.height;
result = prime * result + this.runs;
result = prime * result + this.weight;
return result;
}
最后,这是一个 compareTo:
public int compareTo(Player that)
{
int result;
result = this.family.compareTo(that.family);
if (result != 0) // is the family name different?
{
return result; // yes ... use it to discriminate
}
result = this.given.compareTo(that.given);
if (result != 0) // is the given name different?
{
return result; // yes ... use it to discriminate
}
result = this.age - that.age; // is the age different?
if (result != 0)
{
return result; // yes ... use it to discriminate
}
... (and so on) ...
... with the final one ...
return this.dismisses - that.dismisses; // only thing left to discriminate by
}