I have the following simple code:
class GenClass<T> {
T method1(T in) {
T[] arr = (T[])new Object[10];
arr[1] = in;
return arr[1];
}
}
public class TestClass {
public static void main(String[] args) {
GenClass<Integer> cl = new GenClass<>();
System.out.println(cl.method1(1000));
Integer[] arr = (Integer[])new Object[10];
arr[1] = 1000;
System.out.println(arr[1]);
}
}
The result is the following:
1000
Exception in thread "main" java.lang.ClassCastException:
[Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;
at javaapplication8.TestClass.main(TestClass.java:17)
Java Result: 1
So why this code work well:
T[] arr = (T[])new Object[10];
and this code throw run-time error:
Integer[] arr = (Integer[])new Object[10];
?
Is it because of type erasure?
If so - is "T" at run-time just being exchanged with "Object" in method1 so the source code:
T[] arr = (T[])new Object[10];
became the following at run-time:
Object[] arr = (Object[])new Object[10];
?
Or something different is heppened?