Why does the following test fail in Java?
@Test
public void testUnmodifiableCollection() {
Collection<String> strList = new ArrayList<String>();
strList.add("foo1");
strList.add("foo2");
Collection<String> col1 = Collections.unmodifiableCollection(strList);
Collection<String> col2 = Collections.unmodifiableCollection(strList);
Assert.assertTrue(col1.equals(col2));
}
Because the call to Collections.unmodifiableCollection(Collection)
returns an UnmodifiableCollection
, which does not implement its own equals
method and only implements the Collection
interface. Therefore, Object.equals(Object)
is used which compares the object references with one another. Since you are comparing two different references, the result is false.
The fact that equals
(and hashCode
) are not passed to the underlying collection is also documented in the Javadoc:
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.
See this answer for a good explanation why anything else would violate the contracts of List
s and Set
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With