Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generic Problem

 
gaurav gupta sitm
Greenhorn
Posts: 22
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
what is the difference amongst <?> , <? extends Object> and <Object>
 
Stephan van Hulst
Bartender
Pie
Posts: 5432
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
There is no difference between <?> and <? extends Object>, except that you can't cast a raw type to <? extends Object> without a warning (If I recall correctly).

<Object> is different though. If you have a List<Object>, you may only store actual Object instances in it, not subclasses, like String.
 
Matthew Brown
Bartender
Posts: 4565
8
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Stephan van Hulst wrote:<Object> is different though. If you have a List<Object>, you may only store actual Object instances in it, not subclasses, like String.

That's not right. You can store anything in them (otherwise you'd be breaking the substitution principle).

But you can't assign a List<String> to a List<Object> reference, whereas you can assign a List<String> to a List<?>.
 
Javin Paul
Ranch Hand
Posts: 295
Eclipse IDE Firefox Browser Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

<?> is commonly refereed as wild card and there are three in nature

<?> -- you can assign anything e.g List<String> or List<Integer>
<? extends Object > -- you can assign anything which is either Object of subclass of Object
<? super MyClass> -- you can assign anything which is either MyClass or super class of MyClass.
 
Stephan van Hulst
Bartender
Pie
Posts: 5432
52
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Matthew Brown wrote:
Stephan van Hulst wrote:<Object> is different though. If you have a List<Object>, you may only store actual Object instances in it, not subclasses, like String.

That's not right. You can store anything in them (otherwise you'd be breaking the substitution principle).

But you can't assign a List<String> to a List<Object> reference, whereas you can assign a List<String> to a List<?>.

Oops! I'm sorry, I meant you can't store a reference to a List<String> in a List<Object> variable!
Sorry for the confusion.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic