| Author |
Java downcasting and lists
|
Andy Wilson
Ranch Hand
Joined: Jun 26, 2009
Posts: 30
|
|
I'm a bit confused about the casting rules for the collections API.
If I have an interface, a class that implements that interface, and a method that declares that it returns a list of such interfaces (but which builds a list of instances of the concrete class), then I thought that I should be able to call the method and cast the result of the method to a list of the concrete classes.
Not sure if the above is totally clear, so the following simple code illustrates what I mean:
This all compiles fine. But when I introduce the code below, then I can an "incompatible types" compilation error.
I thought that this should be legal. I'm using the 1.6_027 version of the JDK (64 bit version of windows 2008 server). If I use Jdeveloper and the Oracle Java Compiler (jdeveloper 10.1.3.5) then it compiles and works fine.
Also if I change the client call so that it missing out the types, i.e. to: List myList = service.getListModelObject();
then it compiles and runs OK and I can access the list via getItem() and cast the result of this to ModelObject fine.
Can anyone enlighten me as to what is going on? Am I (and the oracle Java compiler) wrong or is there something up the the JDK javac?
Thanks,
Andy
[Added code tags - see UseCodeTags for details]
|
 |
Andy Wilson
Ranch Hand
Joined: Jun 26, 2009
Posts: 30
|
|
|
Apologies for the repeat of the topic. Looks like there's a few gremlins in the forum. The attempt at posting the other one yielded an error message when I sent it and it didn't appear for several minutes - so naturally assumed it wasn't going to appear and reposted. Then of course it appears.
|
 |
Matthew Brown
Bartender
Joined: Apr 06, 2010
Posts: 3786
|
|
An ModelObject IS-AN IModelObject, but that doesn't mean that a List<ModelObject> IS-A List<IModelObject>. Inheritance of generic types doesn't work like that. The problem is that a List<IModelObject> can contain instances of any class that implements IModelObject. Here's an example that illustrates it:
But now we have an ArrayList<ModelObject> containing an AnotherModelObject, and the type safety that generics are supposed to provide has been broken.
|
 |
Andy Wilson
Ranch Hand
Joined: Jun 26, 2009
Posts: 30
|
|
|
Thanks - makes perfect sense! Bit surprised the Oracle Java compiler allows it.
|
 |
Anayonkar Shivalkar
Bartender
Joined: Dec 08, 2010
Posts: 1295
|
|
Andy Wilson wrote:Thanks - makes perfect sense! Bit surprised the Oracle Java compiler allows it.
Well, it's quite logical. Lets take a standard Animal-Cat-Dog example.
List<Animal> can contain both Cat and Dog. However, precisely because of this fact, we can't say that List<Cat> IS-A List<Animal>.
However, an ArrayList IS-A List. So, there's no problem when you write
I hope this helps.
|
 |
 |
|
|
subject: Java downcasting and lists
|
|
|