How does Guava Set difference work?

guava, java

Solution

The javadoc says:

The returned set contains all elements that are contained by `set1` and not contained by `set2`

It thus means that the rule depends on the type of the two sets. If the Set is a HashSet, for example, `equals()` will be used. If the set is a TreeSet, `compareTo()` (or the comparator's `compare()` method) will be used. If an IdentityHashSet is used, the identity of the object will be used.

`hashCode()` will never be used by any (correct) Set implementation to determine equality, because two unequal objects may have the same hashCode.

Problem

when are two objects considered to be different in `Sets.difference`.When they have a different hash code or when `object.equals` returns a false.

Original source