Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Guava Sets.difference#isEmpty() behaviour

I don't understand the behaviour of Guava's Sets#difference about isEmpty() method :

  public static <E> SetView<E> difference(final Set<E> set1, final Set<?> set2) {
    checkNotNull(set1, "set1");
    checkNotNull(set2, "set2");

    final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
    return new SetView<E>() {
      @Override public Iterator<E> iterator() {
        return Iterators.filter(set1.iterator(), notInSet2);
      }
      @Override public int size() {
        return Iterators.size(iterator());
      }
      @Override public boolean isEmpty() {
        return set2.containsAll(set1);
      }
      @Override public boolean contains(Object element) {
        return set1.contains(element) && !set2.contains(element);
      }
  };
}

More precisely, I don't understand how set2.containsAll(set1); can be used as result of isEmpty().

With an example :

  • set1 = A,B
  • set2 = A,B,C,D,E

the difference (C,D,E) will definitely not be empty. But Sets.difference(set1, set2).isEmpty() will return true as (A,B,C,D,E).containsAll(A,B) is true.

Even if the javadoc says that, I don't understand the logic :

{@code set2} may also contain elements not present in {@code set1}; these are simply ignored

Am I mistaking ? Shall I fill an issue ?

(I'm using guava-18.0)

like image 971
Arno Avatar asked Mar 13 '23 18:03

Arno


1 Answers

From the guava documentation of "public static Sets.SetView difference(Set set1, Set set2)":

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

As you can see none of your set1 meets these criteria, so the difference set is empty.

Note that the difference method is not commutative for the arguments and the difference set is not (C, D, E) as you think when you call difference(set1, set2);

like image 175
DPM Avatar answered Mar 24 '23 08:03

DPM