List list = new ArrayList<String>() ;
list.add(1) ;
Integer hello = (Integer) list.get(0) ;
System.out.println(hello);
The above code has a reference of type List referring to an instance of ArrayList of type String. When the line list.add(1)
is executed, isn't the 1 added to the ArrayList (of type String) ? If yes, then why is this allowed?
You have used type erasure, which means you have ignored previously set generic checks. You can get away with this as this as generics are a compile time feature which isn't checked at runtime.
What you have the same as
List list = new ArrayList() ;
list.add(1) ;
Integer hello = (Integer) list.get(0) ;
System.out.println(hello);
or
List<Integer> list = new ArrayList<Integer>() ;
list.add(1) ;
Integer hello = list.get(0); // generics add an implicit cast here
System.out.println(hello);
If you look at the byte code generated by the compiler, there is no way to tell the difference.
Interestingly, you can do this
List<String> strings = new ArrayList<String>();
@SuppressWarnings("unchecked");
List<Integer> ints = (List) strings;
ints.add(1);
System.out.println(strings); // ok
String s= strings.get(0); // throws a ClassCastException
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