我尝试编写一个程序来存储不相等的对象,包括2个字符串。就此而言,这对(john,bob)被认为等于(bob,john)。我的equals和compareTo实现应该可以正常工作。为了检查什么是错误的,我让我的程序输出我尝试添加的每个新对的比较。看起来像这样:
@Override
public boolean equals(Object o){
if (o==null){
return false;
}
final Pair other = (Pair) o;
return (this.compareTo(other)==0);
}
@Override
public int compareTo (Pair o){
if (this.first.equals(o.first)){
if (this.second.equals(o.second)){
System.out.println("equal: "+this.first+" "+this.second+" and " + o.first+" "+o.second);
return 0;
}
}
else if (this.first.equals(o.second)){
if (this.second.equals(o.first)){
System.out.println("equal: "+this.first+" "+this.second+" and " + o.first+" "+o.second);
return 0;
}
}
System.out.println(" not equal " +this.first+" "+this.second+" and " + o.first+" "+o.second);
return -1;
Exampleinput:
bob john
john john
john john
john bob
bob will
john hohn
如果我让它运行,它将在每次试验后打印出TreeSat的大小以添加新元素。它还将打印compareTo方法中的内容。我添加了注释以指明我的问题。
equal: bob john and bob john //Why comparing the first element at
all?
1
not equal john john and bob john
2
not equal john john and bob john
equal: john john and john john
2
equal: john bob and bob john
2
not equal bob will and bob john
not equal bob will and john john
3
not equal john hohn and john john //no comparision of (john hohn) and
not equal john hohn and bob will //(bob john) why?
4
ONE:回答你的问题:TreeSet不需要比较所有元素,因为元素有一个已定义的顺序。考虑一本字典:在中间打开它,你会立即知道,如果你需要的单词是在该页面之前或之后。你不需要检查字典的两半。
TWO:你的compareTo()方法有问题。考虑两个对象:
Pair a = Pair.of(1, 2);
Pair b = Pair.of(3, 4);
你的compareTo()在两种情况下都会返回-1,但它不能:
a.compareTo(b) == -1
b.compareTo(a) == -1
在数学上说你的关系“compareTo”没有定义订单,因此违反了API合同:
实现者必须确保所有x和y的sgn(x.compareTo(y))== -sgn(y.compareTo(x))。