Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unmodifiable collection equality in Java

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));
}
like image 736
davis Avatar asked Jul 30 '15 20:07

davis


1 Answers

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

See this answer for a good explanation why anything else would violate the contracts of Lists and Sets.

like image 133
hzpz Avatar answered Oct 15 '22 04:10

hzpz