wood burning stoves*
The moose likes Java in General and the fly likes Generic Doubt Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "Generic Doubt" Watch "Generic Doubt" New topic
Author

Generic Doubt

Anudeep Duvvuri
Greenhorn

Joined: May 18, 2012
Posts: 29



the output is
21
class java.lang.Integer

As per my knowledge in java we cannot cast Integer to String or vice versa in java but why is the String Type T is converted to Integer Type here

Please reply.

[Added code tags - see UseCodeTags for details]
Anudeep Duvvuri
Greenhorn

Joined: May 18, 2012
Posts: 29
anyone please clarify me
John Jai
Bartender

Joined: May 31, 2011
Posts: 1776
Please be patient.
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3582
    
  14

Casting is a runtime operation, and at runtime generic type arguments are erased. So type parameters without an upper bound just act as regular Object types. Here's what your class looks like at runtime:
Anudeep Duvvuri
Greenhorn

Joined: May 18, 2012
Posts: 29
Ok got it thank you
that means we can also cast a boolean type right???
Stephan van Hulst
Bartender

Joined: Sep 20, 2010
Posts: 3582
    
  14

You can cast to any generic type parameter, as long as the upper bound is a supertype of the reference you're casting. It doesn't really make much sense though, because you'd always be casting upwards, which is useless.

For instance, if the class signature was public class ImplicitConv<T extends String> then the program would throw a ClassCastException, as expected.
Anudeep Duvvuri
Greenhorn

Joined: May 18, 2012
Posts: 29
Ok thank you very much for replying
Ivan Jozsef Balazs
Rancher

Joined: May 22, 2012
Posts: 867
    
    5
> Here's what your class looks like at runtime:


$javap -private ImplicitConv

Compiled from "ImplicitConv.java"
public class ImplicitConv extends java.lang.Object{
java.lang.Object t;
public ImplicitConv(java.lang.Object);
void method();
public static void main(java.lang.String[]);
}
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3606
    
  60

However, there is a compiler warning ("unchecked cast") on line 7. The compiler has been able to tell something was amiss and told you so. If you ignore or don't resolve generics-related compiler warnings, you risk getting ClassCastException at runtime.
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Generic Doubt
 
Similar Threads
Polymorphism and Instance Variables?
Problem with reference
overloading
Generic method
Examlab generics question