1

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?

Community
  • 1
  • 1
Konstantin Milyutin
  • 11,946
  • 11
  • 59
  • 85

2 Answers2

3

For the compiler, this ? extends Employee means 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.

Community
  • 1
  • 1
Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
  • In my understanding, "? extends Employee" is any type that has Employee as parent. So if we know that collection consists of subtypes of Employees, that we can put there "Managers" and "Part-time workers". But if we consider only one particular subtype, then my assumptions are wrong. – Konstantin Milyutin Aug 24 '12 at 10:32
  • Thank you for PECS, it wasn't on the list when I searched for answer. – Konstantin Milyutin Aug 24 '12 at 10:44
  • You're understanding is a little off. It means One particular type that is a subtype of Employee. It won't match any old Employee object. See this answer i gave for a more detailed explanation. http://stackoverflow.com/questions/11955515/t-extends-aninterface-vs-extends-aninterface/11955957#11955957 – Matt Aug 24 '12 at 12:58
  • @Matt no apparently *your* understanding of my answer is a bit off. I mean the exact same thing you have written in your answer – Sean Patrick Floyd Aug 24 '12 at 13:27
2

Read <? extends Employee> not as "any type extending Employee" but as "a specific but unknown type extending Employee".

wildcardBuddies is still a pair of managers, only now the actual type is now unknown. We know we can get employees out, but we cannot set anything because we don't known if we should set Managers or LowlyEmployees. The Pair<? extends Employee> effectively becomes read-only.

Walter Laan
  • 2,956
  • 17
  • 15