File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Java in General and the fly likes Generics (again) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generics (again)" Watch "Generics (again)" New topic
Author

Generics (again)

Graeme Byers
Ranch Hand

Joined: Apr 16, 2004
Posts: 127
Line (1) (as expected) caused a compile error "Incompatible types".
Line (2) (as expected) executed sucessfully

Line (3) executed successfully.
But why ? I was expecting a compile error because although Integer is a subclass of Number , <Integer> is not a subclass of <Number>.
Thank you.
Pawel Nowacki
Ranch Hand

Joined: Nov 14, 2008
Posts: 67
Actually what you can't do is to declare :

List <Number> numList = new ArrayList <Integer>

but you are allowed to hold Integer values in <Number> List.

See Chapter 7 of SCJP 6 Study Guide Book. Page 613 says:

"(...) So here, we're using polymorphism not for the object that the array
reference points to, but rather what the array can actually HOLD - in this case, any
subtype of Animal. You can do the same thing with generics:



So this part works with both arrays and generics collections - we can add an
instance of a subtype into an array or collection declared with supertype.
(...)
"

Hope this helps,
Paul
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36508
    
  16
More complicated than the average beginner's question. Moving
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36508
    
  16
Whenever you have generics problems, find the Java Tutorials and Angelika Langer's generics FAQ (I haven't got this link at the moment). There is something in the Java Tutorials about Cage<Lion>s and Cage<Butterfly>s which is similar to your problem.
[ December 30, 2008: Message edited by: Campbell Ritchie ]
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics (again)
 
Similar Threads
Generics question
Enhanced For loop for Generics
Generics
Generics question?
Generic Program Warning