I have a generic K and wish to create an empty array so I type
private K[] keys = new K[0];
However eclipse says "Cannot create an generic array of K"
Have I missed something? You can create an empty array of int, is this something generics can't do?
You cannot create arrays of generics in Java. A workaround would be:
keys = (K[])new Object[size];
Although this will generate a compiler warning.
Generally, this is not a good practice and it is not safe to do it. See this thread for more.
However, if you just can't avoid it, it should only be used with new as this casting of an Object array to K[] might be used to insert stuff you won't like.
Update:
But really, as you can see in this answer java.lang.reflect.Array.newInstance() is probably the safer way using the reflection library.
What if K is abstract? How would the executor know how to fill any missing methods?
Also, due to type-erasure upon compilation, you can't tell what class K actually is without comparing it to others, which would require an instance.
Type erasure
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With