If you write
... new ArrayList<Integer>(...
instead, it will throw a compiler exception.
Why does it work:
System.out.println(list.get(0));
The Object.toString() method is the same as in Double and Integer (And since System.out.println() expects the object to not be passed to Integer (the compiler optimized the drop))
Object d = list.get(0); System.out.println(d.getClass());
The same goes for .getClass() . Here, the optimizer dropped the throw again.
System.out.println(list.get(0).getClass());
This actually creates an Integer from the list, and it fails. He throws because the optimizer decided that he needs to do this, because it is not obvious that he does not need it.
If you change this last line to:
System.out.println(((Object)list.get(0)).getClass());
it works:)
Angelo fuchs
source share