hashCode and equals for Collections.unmodifiableCollection()

2.1k views Asked by At

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

There are 1 answers

1
Jacob Mattison On

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.