java – hashCode和equals为Collections.unmodifiableCollection()

前端之家收集整理的这篇文章主要介绍了java – hashCode和equals为Collections.unmodifiableCollection()前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
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进行比较,则两个包装器不应相等.如果你刚刚通过包装清单,他们将是平等的.

原文链接:https://www.f2er.com/java/125082.html

猜你在找的Java相关文章