This week's giveaway is in the EJB and other Java EE Technologies forum. We're giving away four copies of EJB 3 in Action and have Debu Panda, Reza Rahman, Ryan Cuprak, and Michael Remijan on-line! See this thread for details.
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?
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.
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.
Joined: Jun 26, 2009
Thanks - makes perfect sense! Bit surprised the Oracle Java compiler allows it.