I’m currently facing an issue with base and subclasses.
While having a single object as parameter (method single) the compiler doesn’t complain.
But if it comes to lists the compiler forces me to declare the list as <? extends Base>
After that I’m no longer allowed to add objects of the base type to that list.
How can I use both types (Base and Subclass) in one list?
public class Generics {
class Base { }
class Sub extends Base{ }
interface I {
public void list( List<Sub> list );
public void single( Sub p);
}
class C implements I {
public void list( List<Sub> list) { }
public void single( Sub p) { }
}
void test() {
C c = new C();
c.single( new Sub() );
c.list( new ArrayList<Base>() ); // The method list(List<Generics.Sub>) in the type Generics.C is not applicable for the arguments (ArrayList<Generics.Base>)
}
public static void main( String[] args) {
Generics g = new Generics();
g.test();
}
}
Change:
to:
Using just
List<Base>will give you compiler errors like this one:If all you’re going to pass is
List<Base>todoSomethingWith, then this point is moot, since this won’t give you a compiler error. If you want to pass lists that are of a specific type (such asList<Sub>above), then you need to changedoSomethingWithto:This fixes the problem. You could also do it at the caller lever (but it’s a bit messier):
One issue with the wildcard (
?) approach is that you can’t add new items to the list. To do that, you need something like:And then add only
Binstances tobases.