Why can't I create a generic array?

A

Andrea Desole

If I have a generic like

class MyClass<MyType>

it's normal that I can't do something like this:

MyType type = new MyType()

This is because of the type erasure. But what I don't understand is why
Eclipse complains if I do the following:

MyType[] types = new MyType[10]

Apparently I can't create an array of generic types. But why not? What
is the problem? That is just an array of uninitialized objects, type
erasure shouldn't be a problem here, should it?
 
G

Gijs Peek

Andrea said:
If I have a generic like

class MyClass<MyType>

it's normal that I can't do something like this:

MyType type = new MyType()

This is because of the type erasure. But what I don't understand is why
Eclipse complains if I do the following:

MyType[] types = new MyType[10]

Apparently I can't create an array of generic types. But why not? What
is the problem? That is just an array of uninitialized objects, type
erasure shouldn't be a problem here, should it?

Actually, type erasure can pose a problem with generic arrays, which is
exactly why it is disallowed. Look at the following example:

class MyClass<MyType> {
MyType[] types = new MyType[10]; // let's assume this compiles


public void foo() {
Object[] objects = types;
objects[0] = new String(); // does not throw an ArrayStoreException
because the array type has been erased
MyType t = types[0] // Throws a ClassCastException
}
}

Generics are guaranteed to be typesafe, so that's why it is not possible.
 
A

Andrea Desole

Gijs said:
Actually, type erasure can pose a problem with generic arrays, which is
exactly why it is disallowed. Look at the following example:

class MyClass<MyType> {
MyType[] types = new MyType[10]; // let's assume this compiles


public void foo() {
Object[] objects = types;
objects[0] = new String(); // does not throw an ArrayStoreException
because the array type has been erased
MyType t = types[0] // Throws a ClassCastException
}
}

Generics are guaranteed to be typesafe, so that's why it is not possible.

makes sense. I guess I have to get more used to the way generics work.

Thanks
 
E

EJP

Andrea said:
Apparently I can't create an array of generic types.

The issue is partly that an array is already generic with different
semantics, i.e. it allows various derivations of the array type to
appear in it, while a generic array would require all elements to be of
the same type. As the semantics of arrays couldn't be changed, generic
arrays can't be implemented.
 

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
473,769
Messages
2,569,576
Members
45,054
Latest member
LucyCarper

Latest Threads

Top