Take the following generics example
import java.util.List;
import java.util.ArrayList;
public class GenericsTest {
private List<Animal> myList;
public static void main(String args[]) {
new GenericsTest(new ArrayList<Animal>()).add(new Dog());
}
public GenericsTest(List<Animal> list) {
myList = list;
}
public void add(Animal a) {
myList.add(a);
}
public interface Animal {}
public static class Dog implements Animal {}
public static class Cat implements Animal {}
}
It works fine. But as you know, you cannot construct it with
new GenericsTest(new ArrayList<Dog>());
because, as you know, the add(Animal) would make possible to add Cat
s. The suggested way of solving this problem, i.e. wildcarding does not work either, because, yes, you can change every List<Animal>
in List<? extends Animal>
but it has the same problem: you can create the GenericsTest
with List<Cat>
and then add Dog
s.
So my question is: is there a convenient way to write this class once, and then use it for all the possible Animals
? Of course it should solve straightforwardly the above mentioned problem.