Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Adding two sets gives error regarding required and provided types

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>

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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;
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading