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.
我的问题:如果后台集合是一个集合或列表,我希望行为与unmodifiableSet()和unmodifiableList()一致.如何违反hashCode /等于合同?
解决方法
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进行比较,则两个包装器不应相等.如果你刚刚通过包装清单,他们将是平等的.