• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

What is the difference between of using Collection<?> and Collection<Object>

 
santhosh.R gowda
Ranch Hand
Posts: 296
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All,

I want to know the difference between Collection<?> and Collection<Object>



they are telling
Object is not a super type of all kinds of collections


Please can you elaborate this statement because Object is super of all the kinds as i know
 
Christophe Verré
Sheriff
Posts: 14691
16
Eclipse IDE Ubuntu VI Editor
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use the Edit button () to edit your post. I have copy/pasted your second message into the first one this time.
 
Rob Spoor
Sheriff
Pie
Posts: 20512
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Collection<Object> is just that - a Collection with generic type Object. You can retrieve elements as Object references and put any object in it.
Collection<?> is a Collection with an unknown generic type. It could be Integer, String or anything else. Since the type is unknown elements can only be retrieved as references to the common super type -- Object. However, since you don't know the type you can't add anything but null. Anything else might lead to problems later on (e.g. if the actual generic type is Integer and you add a String -- oops!).

So that's the difference: with <?> you can't add anything, with <Object> you can.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic