File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Issue Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Reply Bookmark "Generics Issue" Watch "Generics Issue" New topic
Author

Generics Issue

Chetan Charadva
Greenhorn

Joined: Dec 05, 2008
Posts: 3


Here, Line 1 works fine, but Line 2 gives compilation error. why ?

Can anyone please explain ?

Thanks,
B2.


[HENRY: Added Code Tags]
Henry Wong
author
Sheriff

Joined: Sep 28, 2004
Posts: 16681
    
  19


Here....



Reference variable ls1 is an List of an unknown type that is the super class of Object or Object. Since the Object class doesn't have a superclass, this is the same as saying ls1 is a List of type Object.

So, when the method is called T is an Object type, and this works because a String IS-A Object.

Here....



Reference variable ls2 is an List of an unknown type that is the subclass of Object or Object. Since the Object class is the base class, this is the same as saying ls2 is a List of any unknown type.

Also, keep in mind that the object is a List of Object, but since you didn't declare that info, when you declared your reference variable, the Java compiler doesn't know that during the method call.

So, when the method is called T is an unknown type, and this does not work because an Object cannot be confirmed to be the same unknown type.

Henry


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
Chetan Charadva
Greenhorn

Joined: Dec 05, 2008
Posts: 3
Thanks Henry.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: Generics Issue
 
Similar Threads
Generics
Generics question
Generics problem
Please help with a generic question
Generic Question in JAVA Beat