Possible Duplicate:
Adding an element inside a wildcard type ArrayList
I can’t understand why compiler considers this code wrong:
Pair<Manager> managerBuddies = new Pair<Manager>(ceo, cfo);
Pair<? extends Employee> wildcardBuddies = managerBuddies; // OK
wildcardBuddies.setFirst(lowlyEmployee); // compile-time error
Methods that Pair<? extends Employee> has are:
? extends Employee getFirst()
void setFirst(? extends Employee)
It’s not clear why we can’t set value, because Employee is subtype of ? extends Employee.
Java tutorial tries to explains it, but I still have my question.
Could someone clarify please?
For the compiler, this
? extends Employeemeans one particular subtype of Employee, and the compiler has no way of detecting which subtype that is. So it can’t allow you to insert just any Employee.For more info refer to this question:
What is PECS (Producer Extends Consumer Super)?
or read the Generics FAQ by Angelika Langer.