ArrayList<Integer> arrI = new ArrayList<Integer>();
ArrayList arrO = arrI; // Warning
/* It is ok to add a String as it is an ArrayList of Objects
but the JVM will know the real type, arrO is an arrayList of
Integer...
*/
arrO.add("Hello");
/* How I can get a String in an ArrayList<Integer> ??
Even if the compiler told me that I will get an Integer!
*/
System.out.println(arrI.get(0));
Anybody can explain what’s happening here?
The JVM doesn’t know the real type, because generics are implemented via type erasure.
In terms of bytecode (and therefore runtime behaviour), your code is equivalent to: