Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: Experimenting with generics

Tags:

java

generics

Lastly I experimenting with generics a little bit. I came up with this piece of code:

public class Test {      static <T> void f(T x) {         x = (T) (Integer) 1234;         System.out.println(x);     }      public static void main(String[] args) {         f("a");         f(1);         f('a');         f(1.5);         f(new LinkedList<String>());         f(new HashMap<String, String>());     } } 

I ran this and got this output:

1234 1234 1234 1234 1234 1234 

with no exceptions! How is it possible?

like image 497
tomwesolowski Avatar asked Aug 07 '13 11:08

tomwesolowski


1 Answers

It's because of type erasure (a lot has been written about this, just google for this term). After compiling f to byte code the method might look like this:

static void f(Object x) {     x = (Object) (Integer) 1234;     System.out.println(x); } 

So System.out.println will just call the toString method on object x - and in your case it is Integer.toString().

like image 185
home Avatar answered Sep 19 '22 14:09

home