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

问题描述:

定义了一个实现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无法添加

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值