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:
An
UnmodifiableList
is anUnmodifiableCollection
, but the same is not true in reverse -- anUnmodifiableCollection
that wraps aList
is not anUnmodifiableList
. So if you compare anUnmodifiableCollection
that wraps a Lista
with anUnmodifiableList
that wraps the same Lista
, the two wrappers should not be equal. If you just passed through to the wrapped list, they would be equal.