您的位置:首页 > 其它

compareTo方法重写错误导致TreeSet中无法添加对象

2016-03-02 19:51 501 查看

问题描述:

定义了一个实现Comparable接口的类R,包含一个int变量count。在测试类中添加了一个count为-3的对象后,便无法添加count为1的对象。但是可以添加count比-3小的和count为正数的R对象。

错误原因:

compareTo方法重写错误。

代码:

package test20160302;
import java.util.TreeSet;
class R implements Comparable<Object>{
int count;
public R(int count){
this.count = count;
System.out.println("count:"+count);
}
public String toString(){
return "R[count:"+this.count+"]";
}
public boolean equals(Object obj){
if(this == obj)return true;
if(obj!=null && obj.getClass()==R.class){
return this.count == ((R)obj).count;
}else
return false;
}

public int compareTo(Object obj){
R r = (R)obj;
System.out.println("用来比较的数:"+this.count);
System.out.println("被比较的数:"+r.count);
return this.count<r.count?-1:this.count>1?1:0;
}
}

public class TreeSetTest3 {
public static void main(String[] args) {
TreeSet ts = new TreeSet();
ts.add(new R(-3));
ts.add(new R(-1));
System.out.println(ts);
}
}


输出:

count:-3

用来比较的数:-3

被比较的数:-3

count:-1

用来比较的数:-1

被比较的数:-3

[R[count:-3]]

测试:

- 只添加-3,9,1无法添加

- 只添加9,除0外均可以添加。

- 添加-2,9后,1无法添加

- 添加-1,9后,1无法添加

- 添加-1,2后,1无法添加

- 添加-3后,-1无法添加

- 添加-1后,-3无法添加
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  测试