Collections
类有很多静态辅助方法来提供各种集合类型的只读 View ,比如unmodifiableSet()
, unmodifiableList()
等。对于这些 View 对象,hashCode()
和 equals()
方法将调用转发到基础集合...有一个奇怪的异常(exception):unmodifiableCollection()
.
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.
我的问题:这是在说什么?如果后备集合是集合或列表,我希望行为与 unmodifiableSet()
和 unmodifiableList()
一致。这会如何违反 hashCode/equals 契约?
最佳答案
来自集合的 JavaDoc:
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
。因此,如果您将包装列表 a
的 UnmodifiableCollection
与包装相同列表 a
的 UnmodifiableList
进行比较,两个 wrapper 不应该相等。如果您只是传递给包装列表,它们将是相等的。
关于java - Collections.unmodifiableCollection() 的 hashCode 和 equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851229/