Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Doubt

 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Dear All,

I was solving a mock question of Generics from JavaBeat. The code snippet is given below


It was asked that what are the legal calls for the generic method. All methods except the second call compile.
When i saw the explanation it is written that, call 2 won't work because the compiler cannot guarantee the type
to substitute. I am unable to understand this statement. Can someone explain.

Thanks,
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Check this...



You use the extends then you add the object to that List... You can't do this, when you declaring with the keyword extends.....

Hope it helps.....
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Abhi,

I think so i got your point. Thanks very much.

Best Regards,
 
Abimaran Kugathasan
Ranch Hand
Posts: 2066
Clojure IntelliJ IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Prithvi Sehgal wrote:Hi Abhi,


Hi Abi...

You are Welcome~!
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Sorry mate to put your name wrong. I guess exam pressure is building up and 1 at night, i should really hit the sack.

Thanks again,

 
Tom Reilly
Rancher
Posts: 618
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The method call only allows Collections holding Object instances - not any subtypes of Object - Objects only. This is where generics doesn't do polymorphism on its types.

In the first code (List<? super Object>), you are saying List can contain Object or any class that is a super type of Object (which is none). So that works.

In the second piece of code (List< ? extends Object>), you are declaring a List that can hold Object instances and anything that extends Object (which is everything) and then trying to call the method. That's the reason for the compiler error. The method will only accept a Collection with Object instances.

In the third piece of code (List<Object> ls3) List can only contain Object instances so that works.

The fourth piece of code is the same as the first one.
 
Prithvi Sehgal
Ranch Hand
Posts: 774
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Tom,

Thanks that was very very helpful. I guess this explanation was more meaningful. Silly me, didn't see the signature of
the method properly.

Thanks,
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic