This week's book giveaway is in the OCPJP forum.
We're giving away four copies of OCA/OCP Java SE 7 Programmer I & II Study Guide and have Kathy Sierra & Bert Bates on-line!
See this thread for details.
The moose likes Beginning Java and the fly likes Generics <? super XXX> Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCA/OCP Java SE 7 Programmer I & II Study Guide this week in the OCPJP forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Generics <? super XXX>" Watch "Generics <? super XXX>" New topic
Author

Generics <? super XXX>

Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
Hello,



I am receiving compilation error "Incompatible Types" on the line where I try to assign l.get(0) to a String. What is the return type of get() in case of generics with super keyword. l.get(0) instanceof String returns true.

Thanks in advance for help.


SCJP6
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
You can't tell what the return type is. It is anything which might be a supertype of String, but it is unspecified.

The supertypes of String are String and Object.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19723
    
  20

Or Charsequence, Comparable and Serializable. After all, String implements these interfaces as well.

Campbell is right though; the actual type could be List<Object>, List<Serializable> (also allowing other Serializable objects like Integers) or List<Charsequence> (also allowing StringBuilder for instance). You can still put a String in the List but as the List can contain other objects you can only use the common super type to retrieve elements: Object.


SCJP 1.4 - SCJP 6 - SCWCD 5 - OCEEJBD 6
How To Ask Questions How To Answer Questions
Anup Om
Ranch Hand

Joined: Dec 30, 2009
Posts: 62
Thank you. My understanding is better.

One more question. This is not what we want to do practically. But, why is this allowed? Object is not super class of Serializable.



Thanks.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
Yes, I forgot about CharSequence and Serializable, Rob.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 39478
    
  28
Anything which can be put into a List is an instance; every instance of Serializable is also an instance of Object.
Rob Spoor
Sheriff

Joined: Oct 27, 2005
Posts: 19723
    
  20

Anu Kota wrote:Object is not super class of Serializable.

Object is a super type (not class) of any class or interface. That's because in the end, the root of any inheritance tree is Object.

Remember, generic bounds work with super types. That is broader than super classes; it also includes interfaces, and also array sub typing. String[] is a sub type of Object[] (i.e. you can assign a String[] instance to an Object[] reference) but String[] is not a sub class of Object[].
 
 
subject: Generics <? super XXX>