为什么TransformedCollection没有实现hashCode?

lhu*_*ath 4 java collections guava

我期望两个相同的变换到具有相同的结果对象hashCode.我想使用此属性来检查我的对象是否以有意义的方式更改.

不幸的是,Guava的TransformedCollection extends AbstractCollection(不像AbstractList)没有实现hashCode或等于,并且TransformedCollection本身没有这样的尝试.

  • 我们难道不能根据hashCode迭代器的顺序返回的值计算一个或者这样的值吗?
  • 或者这仍然不能保证相同hashCodes
  • 也许我们可以用一种无法解决TransformedCollection的方式来解决这个问题AbstractCollection

maa*_*nus 11

不幸的是,没有明智的定义方式Collection.hashCode.集合可以是a SetList(或其他),两者hashCode以不兼容的方式定义.

而且,出于同样的原因,没有明确的定义 transformedCollection1.equals(transformedCollection2).它可以忽略顺序,也可以不忽略(Set或List语义).更糟糕的是,返回Collection只是一种观点,这样equals效率会非常低效.

我建议使用类似的东西ImmutableList.copyOf(transformedCollection)并使用它.

  • 或者如果你有一个`List`,使用`Lists.transform`. (3认同)