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?
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()
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With