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?
Gijs Peek - 06 Sep 2006 13:18 GMT
> If I have a generic like
>
[quoted text clipped - 12 lines]
> 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.
Andrea Desole - 06 Sep 2006 13:44 GMT
> Actually, type erasure can pose a problem with generic arrays, which is
> exactly why it is disallowed. Look at the following example:
[quoted text clipped - 12 lines]
>
> 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
EJP - 09 Sep 2006 06:03 GMT
> 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.