This content has been marked as final. Show 2 replies
lnthai2002 wrote:Um... because that's what your method is declared to return: a List<? super E>, where E is inferred to be Integer.
However, i am getting
My code does return a List<Number> and put it in a List<Number> so why it is saying i am returning super of Integer?
found : java.util.List<capture#890 of ? super java.lang.Integer> required: java.util.List<java.lang.Number> output = proces(input);
The book also suggest to change line 4 toA List<? super Integer> is not necessarily a List<Integer>. What if it's actually a List<Number> (which it really is) or List<Object>?
to make it compile but it give me similar error
List<Integer> output = null;
my method is declared to return List<? super E> so inside the method, i can return List<Number> given that E refer to an Integer, right? Because Number is superclass of Integer.
However, since you raise the question about the left-hand side (output) being a fixed type <Integer> while the right hand side is open to return any thing above E - Integer in this case, i think compiler gonna tell when u r trying to assign the incompatible type to the right hand side. But my my example, both the left hand and right hand are the same, just the declaration of the right hand (the return type of the method) is cryptic.
The book say it's possible to use <? super E> in the return type, but I have not succeed in any method declared as such.
Another thing i found strange with the wild card is that it doesnt seem to follow any rules, for example, the following code works:
But this one doesnt work:
Human g1 = new Girl("cindy");//2 humans Human b1 = new Boy("bean"); //so the right hand must be declared as Human //but the left hand can be ? because we dont add, we simply use and Human is a subclass of Human GenericPair<? extends Human,? extends Human> p1 = new GenericPair<Human,Human>(g1,b1);
the error is: cannot find method add(testGeneric.Boy)
List<? extends Human> list1 = new ArrayList<Human>(); list1.add(new Boy("smith")); list1.add(new Human("eve"));
Given that class Boy and Girl extends Human
When i learned generic, i though the rule is "When we USE generic container/class, polymorphisms is allowed-for example, container can be declared to contain superclass object, but we can add object of child class. However, when we DEFINE generic class, polymorphisms is not guaranteed inside the definition"
Any other explanation? I am very appreciate if anyone can teach me the easy way to remember how generic work