gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:22:31 24 4
gpt4 key购买 nike

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com