加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – 为什么ConcurrentSkipListSet.contains需要比较器而不

发布时间:2020-12-15 01:05:56 所属栏目:Java 来源:网络整理
导读:我使用ConcurrentSkipListSet并使用contains方法. 根据JAVA doc for contains方法 如果此set包含指定的元素,则返回true.更正式地说,当且仅当此集合包含o.equals(e)的元素e时才返回true. 但根据我的测试,似乎不使用equals方法,而是比较器是强制性的.请帮助我

我使用ConcurrentSkipListSet并使用contains方法.

根据JAVA doc for contains方法

如果此set包含指定的元素,则返回true.更正式地说,当且仅当此集合包含o.equals(e)的元素e时才返回true.

但根据我的测试,似乎不使用equals方法,而是比较器是强制性的.请帮助我理解JAVA规范和实现之间的这种异常

ConcurrentSkipListSet

/ **
?????*如果使用比较器,则返回ComparableUsingComparator,否则
?????*将密钥转换为Comparable,这可能会导致ClassCastException,
?????*传播回调用者.
?????* /
????私人可比比较(对象键)

at java.util.concurrent.ConcurrentSkipListMap.comparable(ConcurrentSkipListMap.java:663)
????at java.util.concurrent.ConcurrentSkipListMap.doGet(ConcurrentSkipListMap.java:821)
????at java.util.concurrent.ConcurrentSkipListMap.containsKey(ConcurrentSkipListMap.java:1608)

我正在使用Oracle JDK 7

最佳答案
我认为有两个问题/关注点,(1)为什么包含需要Comparator或Comparable. (2)Javadoc说它将使用equals方法.

> ConcurrentSkipListSet是可导航的有序集合,因此所有元素必须保持自然顺序,或者必须指定比较器.
>我认为Javadoc声明不正确,或者至少它具有误导性.在引擎盖下,CSLS将委托给ConcurrentSkipListMap.containsKey,因此它现在不控制contains实现.也就是说,我认为可以有一个论点来澄清javadoc.

编辑:
对于这些对象无法比较的事实,还有一个投掷文档

ClassCastException – if the specified element cannot be compared with
the elements currently in this set

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读