Java does not allow creating generic arrays directly. I understand that due to erasure generic type is not known at runtime, whereas array require type checking at runtime and hence the two are incompatible.
This piece of code does not compile -
Holder<Integer>[] integers = new Holder<Integer>[5];
Fine, but I am unsure why does this piece of code actually compile (with warning for unsafe type conversions)?
Holder<Integer>[] holders = new Holder[5];
holders[0] = new Holder<Integer>(5);
holders[1] = new Holder<Integer>(5);
holders[2] = new Holder<Integer>(5);
I don't exactly understand what did I actually trick the compiler into by removing diamond brackets. Is this an acceptable to create generic arrays?
Further, when I add this line to the code - holders[3] = new Holder<String>("Hello");
It throws a compile error Holder<String> can not be converted to Holder<Integer>
I find this strange because as far as I understand the whole idea of not allowing generic arrays was because arrays could not differentiate between 2 different generic types because of the type erasure. But in this example the compiler can detect incorrect type conversions.
What am I missing here?