Another one of those how do I do toArray() with no warnings questions, but it’s different from most of the ones posted here.
How do I rewrite the method implementation (without changing the method signature) to make it compile without warning?
The apparent difficulty here is that the Class information for T is not available during runtime. However, the return type is an erased type during runtime too, so there’s no really reason that this cannot be done. So, how do I do this if want to enforce compile-time type safety?
Thank you
<T> GenericClass<T>[] toGenericArray(List<GenericClass<T>> list) {
return list.toArray(new GenericClass[0]);
}
You can’t. Because Arrays are covariant, it is impossible to have compile time safety for an array that’s holding a parameterized type. (unless you use < ? > which is legal.)
This will always be legal:
Compiler is unable to protect you from that, so it forces you to acknowledge/suppress that there’s a warning.