While going through some questions on Generics, I came accross the question-
Why can't we have Generic Arrays in Java?
Next, I explored and came accross following article- https://www.baeldung.com/java-generic-array
Now, its mentioned in the article-
An important difference between arrays and generics is how they enforce type checking. Specifically, arrays store and check type information at runtime. Generics, however, check for type errors at compile-time and don't have type information at runtime.
I am not able to properly understand why we can't specify generics for array. Now, I wrote a small program on my own-
package Generics;
import java.util.Arrays;
public class TypeErasure {
private static class GenericClass<T> {
T[] arr; // no error
GenericClass(T[] arr) {
this.arr = arr; // no error
}
void display() {
System.out.println(Arrays.toString(arr));
}
// https://www.geeksforgeeks.org/generics-in-java/
public T[] getArray(int size) {
// T[] genericArray = new T[size]; //compile time error
// return genericArray;
return null;
}
public T[] getArray() {
return arr; // error- Type mismatch: cannot convert from T[] to T[]
// return null;
}
}
public static void main(String[] args) {
GenericClass<Integer> gc = new GenericClass<>(new Integer[] { 1, 2, 3 });
gc.display();
gc.getArray(5);
gc.getArray();
}
}
Following is the de-compiled .class file-
package Generics;
import java.util.Arrays;
public class TypeErasure {
public TypeErasure() {
}
public static void main(String[] var0) {
GenericClass var1 = new GenericClass(new Integer[]{1, 2, 3});
var1.display();
var1.getArray(5);
var1.getArray();
}
private static class GenericClass<T> {
T[] arr;
GenericClass(T[] var1) {
this.arr = var1;
}
void display() {
System.out.println(Arrays.toString(this.arr));
}
public T[] getArray(int var1) {
return null;
}
public T[] getArray() {
return this.arr;
}
}
}
My question-
what problem can occur by making the generic array assignment in the example I have provided? I need to understand the difference between runtime checking and compile time checking and why arrays need to do runtime checking?
Can somebody help me understand why the code commented out in getArray() method gives compile time error?