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 Cats. 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 Dogs.
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.
If I understand what you’re trying to do then you need to put the generic type at class level: