I find the following code remarkable in Java:
ArrayList<String> l1 = new ArrayList<String>();
ArrayList<Integer> l2 = new ArrayList<Integer>();
System.out.println(l1.getClass() == l2.getClass()); // true
System.out.println(l2.getClass().isAssignableFrom(l1.getClass())); // true too
//ArrayList<Integer> l3 = l1; // won't compile though
I don’t quite understand the details of “isAssignableFrom”. Of course, I want the compiler to stop l3 = l2, but it seems to be in contradiction to the previous line? (I’m sure there are subtle points here, that’s what I’m after 🙂
All of the
<Blah>information is stripped away after compile time. As far as the bytecode is concerned, they’re all the same class.When it comes to during the compile, they’re checked for consistency and compatibility.
So when it does the check of
l2.getClass().isAssignableFrom(l1.getClass())it’s sayingis ArrayList assignable from ArrayList?and the answer is yes. But because during the compile it still has type information, it’s not allowed.