Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does TransformedCollection not implement hashCode?

I expect two identical transforms to result objects that have the same hashCode. I'd like to use this property to check whether my object has changed in a meaningful way.

Unfortunately, Guava's TransformedCollection extends AbstractCollection which (unlike AbstractList) does not implement hashCode or equals, and TransformedCollection does no such attempt itself.

  • Could we not calculate a hashCode based on the values as returned by the iterator's order or some such?
  • Or would that still not guarantee identical hashCodes?
  • Perhaps we can solve this problem for TransformedCollection in a way it cannot be solved for AbstractCollection?
like image 918
lhunath Avatar asked Dec 21 '22 17:12

lhunath


1 Answers

Unfortunately, there's no sane way for defining Collection.hashCode. A collection can be a Set or a List (or something else) and the two define hashCode in an incompatible way.

Moreover, for the same reason there's no sane definition for transformedCollection1.equals(transformedCollection2). It could either ignore the order, or not (Set or List semantics). Even worse, the returned Collection is just a view, and such equals would be terrible inefficient.

I'd suggest to use something like ImmutableList.copyOf(transformedCollection) and work with it.

like image 87
maaartinus Avatar answered Dec 24 '22 03:12

maaartinus