hashCode and equals for Collections.unmodifiableCollection()

为君一笑 提交于 2019-12-21 07:16:35

问题


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'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.

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?


回答1:


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.



来源:https://stackoverflow.com/questions/12851229/hashcode-and-equals-for-collections-unmodifiablecollection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!