Question

When I write generic class in Java, I use below code

public ResizableArray() {
    this.count=0;
    this.elements = (T[]) new Object[0];
}

However I get a warning:

Type Safety: Unchecked Cast from Object[] to T[]

Why do I get this warning?

Was it helpful?

Solution

You're creating an Object[] (that is, an array of instances of class "Object", so basically an array of anything). You're casting it into an T[] (that is an array that can ONLY contain instances of class T). You don't test if the objects in the array (I know there are none, but the compiler doesn't) actually IS a T - if it isn't, the cast will throw an ClassCastException at runtime. That's why you get the warning.

OTHER TIPS

If T is anything else but Object, you are basically lying with that downcast. This is because the type of Java arrays, unlike generic types, is reified. In other words,

boolean isStringArray(Object[] os) { return os instanceof String[]; }

called with

System.out.println(isStringArray(new Object[]));

actually prints false: the runtime knows the component type of the array.

What you would really like to do there is return new T[], but you have probably found out this isn't allowed, and it isn't allowed due to exactly the mismatch between generics and array types described above.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top