Java: Experimenting with generics -


lastly experimenting generics little bit. came 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 , got output:

1234 1234 1234 1234 1234 1234 

with no exceptions! how possible?

it's because of type erasure (a lot has been written this, google term). after compiling f byte code method might this:

static void f(object x) {     x = (object) (integer) 1234;     system.out.println(x); } 

so system.out.println call tostring method on object x - , in case integer.tostring().


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -