aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Generics Issue Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Generics Issue" Watch "Generics Issue" New topic
Author

Generics Issue

Chetan Charadva
Greenhorn

Joined: Dec 05, 2008
Posts: 5


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: 18133
    
  39


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: 5
Thanks Henry.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generics Issue
 
Similar Threads
Please help with a generic question
Generics
Generics question
Generics problem
Generic Question in JAVA Beat