Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Generics Issue

 
Chetan Charadva
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator


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
Marshal
Pie
Posts: 20907
76
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

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
 
Chetan Charadva
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thanks Henry.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic