Manoj
Manoj

Reputation: 5867

Erasure in detail?

I am studying generics in Java. I studied that during compilation, erasure erases all the generic info.

Here, i studied that all T is replaced with Object.

 Integer v = display(2);
 String d = display("3");

public <T> T display(T i){
       return i;
    }

I hope it will be turn into

Integer v = (Integer)display(2);
String d = (String) display("3");
public Object display(Object i){
return i;
}

So, is my assumption right?

Thanks.

Upvotes: 4

Views: 145

Answers (3)

Bert F
Bert F

Reputation: 87533

You basically have it. The compiler uses the generic parameter types to validate the code, but the generated bytecode substitutes in a different class.

For an unbound generic parameter like <T>, it would be Object. However, if the declaration were <T extends Comparable>, the substituted class would be Comparable instead of Object.

Edit: Great info about Java Generics, albeit really dense with info in parts:

Java Generics FAQs - Frequently Asked Questions
http://www.angelikalanger.com/GenericsFAQ/JavaGenericsFAQ.html

Upvotes: 4

Maxym
Maxym

Reputation: 11896

information about generic type is not saved into compiled class, it is used only at compile time to check type safety.

Integer v = display(2);

Java compiler knows that that method is "generic", and it returns the same type as its argument, in this case it is Integer, and result is assigned to Integer, so everything is ok.

String d = display("3");

totally the same trick. But in that case:

Long v = display(2);

Java will tell you that it can't cast, because 2 is meant to be Integer, and Java can't cast it to Long, so you need to write:

Long v = display(2L);

As I told, no information is saved into compiled class, so potentially during runtime time you can put into the List<Integer> value of String type, and no exception will be thrown, but when you read this String and try to assign to Integer type variable you will get it... Well, quite tricky ;)

Upvotes: 1

Jochen Bedersdorfer
Jochen Bedersdorfer

Reputation: 4122

Basically, yes. Generics in Java is a nice compiler trick.

Upvotes: 0

Related Questions