Why Didn't The Creators Of Java Allow For Generic Array Intialization?

R

res7cxbi

Just Curious...

Why can't i initialize a generic array like this?

private E[] data = new E[10];

This creates a compiler error saying that i can't intialize generic
arrays
The only workaround i've seen (the Collections class do this too) is
this:

private E[] data = (E[]) new Object[10];

so the question is...

Why Didn't The Creators Of Java Allow For Generic Array Intialization?
 
S

Stefan Schulz

Just Curious...

Why can't i initialize a generic array like this?

private E[] data = new E[10];

This creates a compiler error saying that i can't intialize generic
arrays
The only workaround i've seen (the Collections class do this too) is
this:

private E[] data = (E[]) new Object[10];

so the question is...

Why Didn't The Creators Of Java Allow For Generic Array Intialization?

Because the instruction new E[] would have to become new Object[] (or
whatever) "below the cover", which means that any Object reference could
be stored. While this was once deemed appropriate (since Object [] can be
downcast to any specific array type), it is no longer considered valid.

So, for now we will have to explicitly agree to store any and all kinds of
Objects (new Object[]), and create a more specific view (cast to E[]) of
it. What is annoying is that this technique will still generate a warning
which can only be handled with a @SuppressWarning annotation (if it is
supported by your compiler).
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,432
Messages
2,571,682
Members
48,796
Latest member
Greg L.

Latest Threads

Top