Reputation: 71
To create array of generic, I have seen below recommendation in many websites including this one, too. However, I wonder why we do not use directly the generic class in array creation. What is the reason to push us to not use below array creation method?
What currently is used
public class X<T> {
private Y<T> tTypeClass = null;
public T[] Array() {
T[] array = (T[]) Array.newInstance(tTypeClass.getObject().getClass(),4);
}
}
Why we do not use
public class X<T> {
public T[] arrayCreation() {
T[] array = (T[]) Array.newInstance(this.getClass(),4);
}
}
Upvotes: 1
Views: 56
Reputation: 48837
Because the cast is not safe. For example:
String[] s = new X<String>().arrayCreation();
will result in java.lang.ClassCastException
.
Upvotes: 0
Reputation: 5607
You can't write code like T[] arr = new T[xx]
because Java generics are type-erased. The Runtime has no idea what T
is during runtime, because the Java compiler replaced all generics with casts at compile time.
Also,
public class X<T> {
public T[] arrayCreation() {
T[] array = (T[]) Array.newInstance(this.getClass(),4);
}
}
will cause a ClassCastException because it creates an array of X[]
and tries to cast it to T[]
.
Upvotes: 1