I’m trying to find a way in which I can return a generic set, which will accept subtypes. The code below returns a Set<? extends A> to which I’m trying to add a B.
import java.util.Set;
import java.util.HashSet;
public class Test {
private static class A {}
private static class B extends A {}
public Set<? extends A> getSet() {
return new HashSet<B>();
}
public void work() {
getSet().add(new B()); // compile error
}
}
Which results in the following error:
Test.java:13: cannot find symbol
symbol : method add(Test.B)
location: interface java.util.Set<capture#320 of ? extends Test.A>
getSet().add(new B());
The generic wildcard tutorial states that B cannot be added to a Set<? extends A> because we don’t know if B is a subtype of A, but I have just defined it as such. Can someone clarify this for me?
That’s fundamentally impossible.
What if the method actually returns a
HashSet<C>?You just added a
Bto a set ofCs.The method’s contents (
returnstatement) are ignored when checking typesafety.If you want to do this, you should just return an ordinary
HashSet<A>.