tags:

views:

88

answers:

2

the code:(the line that will show the compile-error is 3 )

Pair<Manager> managerBuddies = new Pair<Manager>(ceo, cfo);
Pair<? extends Employee> wildcardBuddies = managerBuddies; // OK
wildcardBuddies.setFirst(lowlyEmployee); // compile-time error

the error is about "No corruption is possible"

and what is the type of wildcardBuddies?(Pair<? extends Employee> or Pair<Manager>)

+1  A: 

I found this: http://userpages.umbc.edu/~edelman/341/Generics.pdf

It describes the exact problem.

Mike Mu
This question is straight out of that document. The JDK does not even give the error described "No corruption is possible" (that's in the document though), it gives "The method setFirst(capture#1-of ? extends Employee) in the type Pair<capture#1-of ? extends Employee> is not applicable for the arguments (Employee)"
stevedbrown
Yes, the question is straight out of the document, but below it is the answer. Unless the asker is confused about the answer in the document?
Mike Mu
+2  A: 

The reason that code results in an error is because there is no way of knowing what specific subclass of Employee wildcardBuddies will accept. Why is the compiler unsure? To see that, we look more closely at the code:

Pair<Manager> managerBuddies = new Pair<Manager>(ceo, cfo);

Here we create a Pair of Managers, which is a subclass of Employee.

Pair<? extends Employee> wildcardBuddies = managerBuddies; // OK

Here, we assign the pair we just created to a Pair of objects which must be Employee or a subclass thereof. Note that we are not creating a new object here, just making a second reference to the first Pair.

wildcardBuddies.setFirst(lowlyEmployee); // compile-time error

Now we try to do something that shouldn't be allowed for the simple reason that lowlyEmployee is not a Manager. Remember that although wildcardBuddies is a reference to a pair of Employee subtypes, the object it points to is quite specifically a pair of Managers, and conversion from a superclass (Employee) to a subclass (Manager) is not allowed. Since the compiler cannot check for all possible scenarios where calling setFirst() would be allowed on the actual underlying object with the given arguments, it has a rule that will disallow all illegal behaviour, as well as some legal behaviour.

Hope this helps explain the answer in the PDF better. Please someone correct me if I'm wrong on anything.

Sean Nyman