I've seen people saying that creating an array like this is a bad
idea, due to it being not type safe. However, every time I use it, I
have no problems with it. When would creating an array like this cause
a problem?
People say it is a bad idea because, logically, it is not correct to cast an object whose runtime type is Object[]
to type T[]
if T
is not Object
.
However, you do not see any immediate problems because, inside the class (within the scope of T
), T
is erased. So the cast from Object[]
to T[]
is not checked.
If all you ever do is use this variable inside your class (inside the scope of the type variable T
), and you never return it to people outside of the class and there is no way people outside of the class can get access to it, then it will not cause any problems.
In fact, there are benefits to the way you're doing it -- you get all the benefits of generic type checking when getting and setting elements of the array, which you would not get if you simply followed the completely "type-safe" solution of using a variable of type Object[]
, in which case you would have to manually cast things you get out of it.
You will get a problem if you ever return this array variable to the outside (or otherwise allow the outside to access it) as type T[]
, because the calling code will expect a certain type of array, and the generics will insert a cast in the calling code when it receives this array, and the cast will fail at runtime (since e.g. a Object[]
is not a String[]
; they are different types at runtime). Here is a simple example:
public class aClass<T> {
private T[] elements;
public aClass(T[] elements) {
this.elements = elements;
}
public void doSomething() {
elements = (T[]) new Object[5];
...
}
public T[] getArray() {
return elements;
}
}
// some other code...
aClass<String> foo = new aClass<String>(new String[2]);
foo.doSomething();
String[] bar = foo.getArray(); // ClassCastException here