直接来自这个API即 Collections.synchronizedCollection(Collection)
:
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.
这是否意味着如果我有重写的方法 equals
和 hashCode
,这些重写的方法将不会被考虑在内?如果是,为什么?这是相当误导...
最佳答案
假设 equals()
只是委托(delegate)给后备集合,并假设这个后备集合是 ArrayList list
。
然后你会有
Collections.synchronizedCollection(list).equals(list) == true
因为它将通过委托(delegate)给 list.equals(list)
来实现。
但是你会有
list.equals(Collections.synchronizedCollection(list)) == false
因为列表不能等于不是列表的集合,并且 Collections.synchronizedCollection(list)
不是列表。
这会严重破坏 Object.equals()
的约定。如果要保持相等性,请使用 Collections.synchronizedList()
同步 List,并使用 Collections.synchronizedSet()
同步 Set。
关于java - 关于阻塞同步集合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17741898/