0

Here is some code that I was trying to understand

public static <E> Sets.SetView<E> difference(final Set<E> set1, final Set<?> set2) {
    Preconditions.checkNotNull(set1, "set1");
    Preconditions.checkNotNull(set2, "set2");
    final Predicate<Object> notInSet2 = Predicates.not(Predicates.in(set2));
    return new Sets.SetView<E>() {
        public Iterator<E> iterator() {
            return Iterators.filter(set1.iterator(), notInSet2);
        }

        public int size() {
            return Iterators.size(this.iterator());
        }

        public boolean isEmpty() {
            return set2.containsAll(set1);
        }

        public boolean contains(Object element) {
            return set1.contains(element) && !set2.contains(element);
        }
    };
}

I am confuse on what the function is returning, when I use it, it would seems like the function is returning Sets.SetView<E>

For example

        Set<Integer> a = new HashSet<>();
        Set<Integer> b = new HashSet<>();
        a.add(1);
        Sets.difference(a, b); // is of type Sets.SetView<Long>

What is the extra <E> prepend in front?

And why does the actual return value contains method definition?

    return new Sets.SetView<E>() {
        public Iterator<E> iterator() {
            return Iterators.filter(set1.iterator(), notInSet2);
        }

        public int size() {
            return Iterators.size(this.iterator());
        }

        public boolean isEmpty() {
            return set2.containsAll(set1);
        }

        public boolean contains(Object element) {
            return set1.contains(element) && !set2.contains(element);
        }
    };
user10714010
  • 865
  • 2
  • 13
  • 20
  • It's a generic method. https://docs.oracle.com/javase/tutorial/extra/generics/methods.html – markspace Dec 06 '18 at 00:49
  • When you pass it a set of Integer, for example, it returns a `SetView`. That's all it means. The type of set you pass it is the type of SetView it returns. – markspace Dec 06 '18 at 00:51
  • `why does the actual return value contains method definition` That's an anonymous class. https://docs.oracle.com/javase/tutorial/java/javaOO/anonymousclasses.html You really need to study up on Java syntax. – markspace Dec 06 '18 at 00:53
  • The "extra" `` in front is the type parameter declaration. A type parameter must be declared before it can be used. – dnault Dec 06 '18 at 00:55

1 Answers1

0

Don't read as <E> Sets.SetView<E>. The method returns Sets.SetView<E>. the prepend <E> is the generic template syntax on static method.

exudong
  • 366
  • 3
  • 13