为什么下面的测试在 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
'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.
参见 this answer为了很好地解释为什么其他任何东西都会违反 List
和 Set
的约定。
关于java - Java 中不可修改的集合相等性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31733537/