I have some confusion about generic programming in java:
If Manager is subclass of Employee,
Collection<Manager> managers=new Collection<Manager>;
Collection<Employee> employees=managers;//why illegal?
Why the last statement is illegal?
Since according to illustration in the book CORE JAVA,after
the erasion,Collection<Manager> and Collection<Employee> are
all converted into raw type Collection.
If the above were true, then you could take your collection of managers, treat it as a collection of employees, and then put any employee into a collection of managers (i.e. not just a manager, but a (say) graduate trainee, a CIO etc.)
It's a little counter-intuitive. An orange is a fruit. A list of oranges is not a list of fruit (otherwise you could put an apple in it). There's a concise explanation in the Java Generics Tutorial.
This is called covariance and contravariance. The issue you just discovered is a traditional problem of type systems. The corresponding wikipedia page discusses this issue in Java. It's worth taking some time to understand these issues correctly has it also relates also to method overriding (since JDK5, you can indeed change the return type of an overriden method as long as it's covariant).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With