Collections.unmodifiableCollection()的hashCode和equals [英] hashCode and equals for Collections.unmodifiableCollection()
问题描述
集合
类有一些静态辅助方法来提供各种集合类型的只读视图,例如 unmodifiableSet()
, unmodifiableList()
等。 c $ c> equals()方法向底层集合转发调用...有一个奇怪的异常: unmodifiableCollection()
。
JavaDoc 明确指定:
返回的集合不会传递hashCode equals
和
hashCode / code>方法。
我的问题:这是为了保留这些操作的合同,在后台集合是一个集合或列表的情况下。 wtf是这个谈论??如果后台集合是一个集合或一个列表,我期望行为与 unmodifiableSet()
和 unmodifiableList()
。
从集合的JavaDoc:
$ Object.quals方法的一般合同规定equals
必须是对称的(换句话说,a.equals(b)当且仅当
< b。等量(a))。 List.equals和Set.equals的合同表明
列表只等于其他列表,并设置为其他集合。因此,一个
自定义equals方法的集合类实现既不
List或Set接口必须返回false,当这个集合是
相比,任何列表或集合。 (同样的逻辑,不可能
编写一个正确实现Set和List
接口的类。)
UnmodifiableList
是一个 UnmodifiableCollection
,但是相反不是真的 - code> UnmodifiableCollection 包装列表
不是 UnmodifiableList
。所以,如果你比较一个 UnmodifiableCollection
,它将List a 与
UnmodifiableList
包装同一个List a
,两个包装不应该相等。如果你刚刚通过包装的列表,他们会是平等的。
The Collections
class has a number of static helper methods to provide read-only views of various collection types, such as unmodifiableSet()
, unmodifiableList()
, etc. For these view objects, the hashCode()
and equals()
methods forward calls to the underlying collection... With one odd exception: unmodifiableCollection()
.
The JavaDoc explicitly states:
The returned collection does not pass the hashCode and equals operations through to the backing collection, but relies on
Object
'sequals
andhashCode
methods. This is necessary to preserve the contracts of these operations in the case that the backing collection is a set or a list.
My question: wtf is this talking about?? If the backing collection is a set or a list, I'd expect behavior consistent with unmodifiableSet()
and unmodifiableList()
. How would that violate the hashCode/equals contracts?
From the 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.)
An UnmodifiableList
is an UnmodifiableCollection
, but the same is not true in reverse -- an UnmodifiableCollection
that wraps a List
is not an UnmodifiableList
. So if you compare an UnmodifiableCollection
that wraps a List a
with an UnmodifiableList
that wraps the same List a
, the two wrappers should not be equal. If you just passed through to the wrapped list, they would be equal.
这篇关于Collections.unmodifiableCollection()的hashCode和equals的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!