Guava Sets.difference # isEmpty () behavior

I do not understand the behavior of the Guava Sets # difference in the 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 do not understand how set2.containsAll(set1);it can be used as a result isEmpty().

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 javadoc says that I do not understand the logic:

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

Am I mistaken? Should I fill out a question?

(I am using guava-18.0)

+4
source share
1 answer

guava "public static Sets.SetView difference (Set set1, Set set2)":

, set1 set2

, set1 , .

, , (C, D, E), , difference(set1, set2);

+6

Source: https://habr.com/ru/post/1622327/


All Articles