Whats the reason I cant create generic array types in Java?

Whats the reason I cant create generic array types in Java?

Its because Javas arrays (unlike generics) contain, at runtime, information about its component type. So you must know the component type when you create the array. Since you dont know what T is at runtime, you cant create the array.

Quote:

Arrays of generic types are not
allowed because theyre not sound. The
problem is due to the interaction of
Java arrays, which are not statically
sound but are dynamically checked,
with generics, which are statically
sound and not dynamically checked.
Here is how you could exploit the
loophole:

class Box<T> {
    final T x;
    Box(T x) {
        this.x = x;
    }
}

class Loophole {
    public static void main(String[] args) {
        Box<String>[] bsa = new Box<String>[3];
        Object[] oa = bsa;
        oa[0] = new Box<Integer>(3); // error not caught by array store check
        String s = bsa[0].x; // BOOM!
    }
}

We had proposed to resolve this
problem using statically safe arrays
(aka Variance) bute that was rejected
for Tiger.

gafter

(I believe it is Neal Gafter, but am not sure)

See it in context here: http://forums.sun.com/thread.jspa?threadID=457033&forumID=316

Whats the reason I cant create generic array types in Java?

By failing to provide a decent solution, you just end up with something worse IMHO.

The common work around is as follows.

T[] ts = new T[n];

is replaced with (assuming T extends Object and not another class)

T[] ts = (T[]) new Object[n];

I prefer the first example, however more academic types seem to prefer the second, or just prefer not to think about it.

Most of the examples of why you cant just use an Object[] equally apply to List or Collection (which are supported), so I see them as very poor arguments.

Note: this is one of the reasons the Collections library itself doesnt compile without warnings. If you this use-case cannot be supported without warnings, something is fundamentally broken with the generics model IMHO.

Leave a Reply

Your email address will not be published.