wood burning stoves 2.0*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics Doubt" Watch "Generics Doubt" New topic
Author

Generics Doubt

Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
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,

Prithvi,
My Blog, Follow me on Twitter,Scjp Tips, When you score low in mocks, Generics,Scjp Notes, JavaStudyGroup
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

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.....


|BSc in Electronic Eng| |SCJP 6.0 91%| |SCWCD 5 92%|
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
Hi Abhi,

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

Best Regards,
Abimaran Kugathasan
Ranch Hand

Joined: Nov 04, 2009
Posts: 2066

Prithvi Sehgal wrote:Hi Abhi,


Hi Abi...

You are Welcome~!
Prithvi Sehgal
Ranch Hand

Joined: Oct 13, 2009
Posts: 774
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

Joined: Jun 01, 2010
Posts: 618
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

Joined: Oct 13, 2009
Posts: 774
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,
 
 
subject: Generics Doubt