JAVA SortedSet的坑
来源:互联网 发布:怎么锻炼丁丁变粗 知乎 编辑:程序博客网 时间:2024/05/18 16:16
今天在用ConcurrentSkipListSet的时候,发现有些对象在调用add方法时,返回false。调用contains方法返回true,说明元素在set中已经存在了,但实际上没有。首先,我先查看java帮助,contains方法是这么说的:
“Returns true if this set contains the specified element. More formally, returns true if and only if this set contains an element e such that o.equals(e).”
根据上面的说明,我尝试了下,但在此时踩到坑:
System.out.println("check 1:"+taskset.contains(tk)); boolean contains = false; for(WfTask t:taskset) { if(tk.equals(t)) { contains = true; } } System.out.println("check 2:"+contains);
运行结果缺是:
check 1:true
check 2:false
结果明显和java帮助说明不一样嘛。也就是说,在set中,不只通过equals判断是否重复。
但是,将ConcurrentSkipListSet 替换成hashset,则不存在上述问题。treeset也同样存在上述问题。
可见,上述问题与排序有关。
通过检查自定义的排序方法,发现添加不进去的元素,都是与set中的元素比较大小时,产生的相等的结果,即compare 接口返回0。
由此可见,对于hashset,是否重复只通过equals判断。
但对于SortedSet,如ConcurrentSkipListSet 或TreeSet,不但要通过equals判断,还要通过compare 方法判断是否与set中的元素存在相等情况,若存在相等,也不能加入。
1 0
- JAVA SortedSet的坑
- java类集中的SortedSet接口
- JAVA类集----SortedSet接口
- java SortedSet接口
- Java类集-SortedSet接口
- Java中SortedSet
- Java记录 -59- SortedSet
- java类集---SortedSet接口
- sortedset
- SortedSet
- java SortedSet接口swap方法
- [疯狂Java]集合:SortedSet、TreeSet
- Java 集合SortedSet&SortedMap讲解
- redis数据类型SortedSet的常用命令
- 对象容器 - Java对数据结构的封装 - List, ArrayList, LinkedList, Set, SortedSet, HashSet, Map, TreeMap
- java API 学习2 Deque,SortedSet,Semaphore
- Java集合之Set、SortedSet、NavigableSet
- 探讨 .NET 4 新增的 SortedSet 类
- linux中PCI总线驱动
- 21个优质Swift开源App
- java 反射解析,将反射用于工厂模式【实例】
- 团队的建设与管理-献给每一位奋斗的同事
- 统计字符数
- JAVA SortedSet的坑
- 大数据分析之聚类算法
- Lightoj1216——Juice in the Glass (计算几何)
- crontab执行后邮件发到指定邮箱
- cocoa 框架参考
- Sys和system用户的区别,as normal、sysdba 和sysoper系统权限区别
- OPC添加组和添加项--------OPC(第六篇)
- Uboot常用命令小结Booting the Kernel (with mmcblk/SD card rootfs)
- 阿里云定时备份mysql