java - Java 中不可修改的集合相等性

标签 java collections equals

为什么下面的测试在 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));
}

最佳答案

因为调用 Collections.unmodifiableCollection(Collection) 返回一个 UnmodifiableCollection,它没有实现自己的 equals 方法,只实现了集合 接口(interface)。因此,使用 Object.equals(Object) 将对象引用相互比较。由于您比较的是两个不同的引用文献,因此结果是错误的。

Javadoc 中也记录了 equals(和 hashCode)未传递给基础集合的事实:

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.

参见 this answer为了很好地解释为什么其他任何东西都会违反 ListSet 的约定。

关于java - Java 中不可修改的集合相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733537/

相关文章:

java - java中如何对数组列表进行排序

Java equals 方法。如何返回比较对象内每个属性的多个 boolean 值

java - Apache Commons ObjectUtils equals 方法测试什么样的相等性?

java - HashCodeBuilder 的使用,以及 Java 如何以及为何为具有字段的对象计算 hashCode?

java - Apache Storm Trident 和 Kafka Spout 集成

java - 在 Java 中创建一个数组来存储泛型类型

c# - 使用另一个集合实现一个集合

java - Lambda 表达式将对象从一个列表添加到另一种类型的列表

java - View 排序和过滤 : GlazedList sorting and filtering + JTable vs Glazed event list+JXTable

java - 当前修改异常 Android 迭代器