Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics <? super XXX>

 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 20552
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Anup Om
Ranch Hand
Posts: 62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yes, I forgot about CharSequence and Serializable, Rob.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49447
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Anything which can be put into a List is an instance; every instance of Serializable is also an instance of Object.
 
Rob Spoor
Sheriff
Pie
Posts: 20552
57
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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[].
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic