aspose file tools*
The moose likes Beginning Java and the fly likes Generics, Collections and Intefaces Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of The Java EE 7 Tutorial Volume 1 or Volume 2 this week in the Java EE forum
or jQuery UI in Action in the JavaScript forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics, Collections and Intefaces" Watch "Generics, Collections and Intefaces" New topic
Author

Generics, Collections and Intefaces

Alfred Lysebraate
Greenhorn

Joined: Jul 22, 2008
Posts: 3
Hello everybody. This is my first post on this forum, and it is about Java generics.
Is there a obvious reason why the code below does not compile? The compiler can clearly figure out that Car implements the contract of a vehicle?!
Does this have something to do with type erasure in Java?

Thanks.

Joanne Neal
Rancher

Joined: Aug 05, 2005
Posts: 3456
    
  12
Think about the following codeIf you knew nothing about the getVehicles method you would think it would be fine. But the getVehicles method is actually returning a List that was defined to contain only Cars, but you are trying to add a Bus to that List.


Joanne
Alfred Lysebraate
Greenhorn

Joined: Jul 22, 2008
Posts: 3
I did not see that right away, but a rather simple reasoning. Thank you!
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19672
    
  18

You could solve it by having the repo return a List<? extends Vehicle> instead. Now you can return List<X> where X is either Vehicle, a sub interface, or an implementation of Vehicle or a sub interface.

The issue with List<? extends Vehicle> is that, like Joanne has shown, you cannot add anything since the compiler doesn't know exactly what the ? stands for.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
 
It is sorta covered in the JavaRanch Style Guide.
 
subject: Generics, Collections and Intefaces