Dienstag, 17. Januar 2012

How to create a generic Array?

Did you ever tried something like this?

final T[] newArray = new T[10];

..Well what you get is a compiler error: "Cannot create a generic array of T".
The reason for this is, that arrays need type information at runtime, i believe because of their covariance (which basically means String[] extends Object[] and therefore the type must be checked at runtime to ensure type safety).

Anyway since after type erasure takes place every type information is lost there is just no way that this should be allowed. So what can we do? Lets take a jump into the world of reflection...

public static T[] createTypeSafeArray(final Class clazz, final int length) {
return (T[]) Array.newInstance(clazz, length);
}

With this we can easily create for example a String array of size 10:

final String[] myStrArray = createTypeSafeArray(String.class, 10);


Pretty cool ehh? :D

1 Kommentar:

Anonym hat gesagt…

yeah it is, nice job dude and thanks for sharing :)