I encounter the problem of using wild cards in collections. It is similar to the question in java generic and wild card but the responses there I found confuse. Could please advise?
Problem: I would like to use a collection with a class and its subtypes. On basis of the docs, I expected I have to use the <? extends myclass>
but it does not work with that, however without using it, it works smoothly. Why is it this way, it should exactly be opposit? Is it the same with the <? super myclass>
for super classes?
The correct example:
List<Number> nl = new ArrayList<>();
nl.add(new Integer(2));
System.out.println("===> List<Number>.add (new Integer(2)) = " + nl.get(0));
The incorrect example:
List<? extends Number> nl = new ArrayList<>();
nl.add(new Integer(2));
System.out.println("===> List<Number>.add (new Integer(2)) = " + nl.get(0));
I would appreciate your advice. Thanks a lot, Tamas