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无法添加
相关文章推荐
- Android之使用Http协议实现文件上传功能
- mysql集群之MMM简单搭建
- 通晓网络测试常用命令
- Nodejs学习笔记之测试驱动
- 可以测试javascript运行效果的代码
- 使用php测试硬盘写入速度示例
- python 测试实现方法
- 如何测试端口通不通(四种方法)
- 举例详解PHP脚本的测试方法
- Php-Redis安装测试笔记
- mysql压力测试脚本实例
- JavaScript 组件之旅(四):测试 JavaScript 组件
- js简单网速测试方法完整实例
- Android触屏测试实例代码
- 解析libcurl在android下的移植、编译与测试
- 几个比较实用的JavaScript 测试及效验工具
- Java中对AtomicInteger和int值在多线程下递增操作的测试
- Python实现测试磁盘性能的方法
- python自动化测试实例解析
- Python之PyUnit单元测试实例