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);
}
};