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