Search code examples
guavahashset

Guava Sets intersection(HashSet1, HashSet2) compares by hash or by value?


When using Guava Sets to come up with the intersection of two HashSets, how does it determine that two elements are identical? By their value or by their hash?

== Update ==

Looking at the source code of java.util.HashSet, I realize that contains() actually calls containsKey() to do the comparison:

HashSet.contains


Solution

  • Hashes are never, ever used to determine equality. That's not their goal. Their goal, in a hash-based collection, is to reduce the number of potentially equal candidates.

    intersection() returns a view over two sets, so it completely delegates the equality tests to the underlyong two Sets.