简体   繁体   中英

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));
}

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 List s and Set s.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM