I’m trying to combine two sets a and b:
Set<? extends Element> a = getSetA();
Set<? extends Element> b = getSetB();
Set<? extends Element> c = new HashSet<>(a);
c.addAll(b);
But I’m getting this error on last line:
Required type: Collection<? extends capture of ? extends Element>
Provided: Set<capture of ? extends Element>
>Solution :
You cannot add elements to a Set<? extends Element>. See also Producer Extends Consumer Super. Set<? extends Element> would be a "producer" of Elements.
There is absolutely no need to declare c as Set<? extends Element>. Its type can just be Set<Element>, then the addAll call is valid.
Set<? extends Element> a = getSetA();
Set<? extends Element> b = getSetB();
Set<Element> c = new HashSet<>(a);
c.addAll(b);
// if you really like Set<? extends Element>, feel free to:
Set<? extends Element> d = c;