Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java creating a array of type generic [duplicate]

Tags:

java

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?

like image 383
Zimm3r Avatar asked Jun 12 '26 17:06

Zimm3r


2 Answers

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.

like image 132
Artem Tsikiridis Avatar answered Jun 15 '26 07:06

Artem Tsikiridis


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

like image 24
Obicere Avatar answered Jun 15 '26 07:06

Obicere



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!