java - Collections.unmodifiableCollection() 的 hashCode 和 equals

标签 java collections unmodifiable

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'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/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。因此,如果您将包装列表 aUnmodifiableCollection 与包装相同列表 aUnmodifiableList 进行比较,两个 wrapper 不应该相等。如果您只是传递给包装列表,它们将是相等的。

关于java - Collections.unmodifiableCollection() 的 hashCode 和 equals,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12851229/

相关文章:

c# - WPF:从绑定(bind)列表中删除最后一项的最有效方法?

java - 不同步 Java 集合的后果

java - 如何创建深度不可修改的集合?

java - 方法 unmodifiablelist() 不能应用于给定类型

java - 如何读取CSV文件并对数据进行操作?

java - 如何捕获 throws 子句中列出的异常

java - 将方法转换为具有多种数据类型的泛型

java - 从迭代器的 next 方法中获取 ClassCastException

java - 转换不可修改的集合

java - 如何通过java调用NetDocuments SOAP API?