我尝试编写一个存储非相等对对象的程序,由2个字符串组成。就此而言,这对(约翰,鲍勃)被认为是等于(鲍勃,约翰)。我的等价和比较到实现应该工作正常。为了检查出了什么问题,我让我的程序输出为我尝试添加的每个新对所做的比较。看起来像这样:
@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;
示例输入:
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
慕妹3242003
相关分类