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

java – hashCode和equals为Collections.unmodifiableCollection

发布时间:2020-12-14 16:32:31 所属栏目:Java 来源:网络整理
导读:Collections类有一些静态帮助方法来提供各种集合类型的只读视图,如unmodifiableSet(),unmodifiableList()等.对于这些视图对象,hashCode()和equals()方法将调用转发到底层集合…有一个奇怪的例外:unmodifiableCollection(). JavaDoc explicitly states: The
Collections类有一些静态帮助方法来提供各种集合类型的只读视图,如unmodifiableSet(),unmodifiableList()等.对于这些视图对象,hashCode()和equals()方法将调用转发到底层集合…有一个奇怪的例外:unmodifiableCollection().

JavaDoc explicitly states:

The returned collection does not pass the hashCode and equals operations through to the backing collection,but relies on Object‘s equals and hashCode methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.

我的问题:如果后台集合是一个集合或列表,我希望行为与unmodifiableSet()和unmodifiableList()一致.如何违反hashCode /等于合同?

解决方法

从JavaDoc for Collection:

The general contract for the Object.equals method states that equals
must be symmetric (in other words,a.equals(b) if and only if
b.equals(a)). The contracts for List.equals and Set.equals state that
lists are only equal to other lists,and sets to other sets. Thus,a
custom equals method for a collection class that implements neither
the List nor Set interface must return false when this collection is
compared to any list or set. (By the same logic,it is not possible to
write a class that correctly implements both the Set and List
interfaces.)

一个UnmodifiableList是一个UnmodifiableCollection,但相反的是不相反的 – 一个UnmodifiableCollection包装一个List不是一个UnmodifiableList.因此,如果将一个包含List a的UnmodifiableCollection与包含同一个List a的UnmodifiableList进行比较,则两个包装器不应相等.如果你刚刚通过包装清单,他们将是平等的.

(编辑:李大同)

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

    推荐文章
      热点阅读