Why is Generic Array Creation not Allowed in Java? | TO THE NEW Blog
To understand this topic let us directly start with an example.
List<Integer> arrayOfIntegerList[] = new ArrayList<>[10]; // compile time error !!
You will find that a simple statement like this will not even compile because the Java compiler does not allow this. To understand the reason, you first need to know two arrays are covariant and generics are invariant.
Covariant: It means you can assign subclass type array to its superclass array reference. For instance,
Object objectArray[] = new Integer[10]; // it will work fine
Invariant: It means you cannot assign subclass type generic to its super class generic reference because in generics any two distinct types are neither a subtype nor a supertype. For instance,
List<Object> objectList = new ArrayList<Integer>(); // won't compile
Because of this fundamental reason, arrays and generics do not fit well with each other.
Now let's get back to the actual question. If generic array creation were legal, then compiler generated casts would correct the program at compile time but it can fail at runtime, which violates the core fundamental system of generic types.
Read full article from Why is Generic Array Creation not Allowed in Java? | TO THE NEW Blog
No comments:
Post a Comment