Java’s broken generics

By: on July 18, 2005

Having been helping and tinkering with a functional library for Java, I’ve come across real issues with Java and its arrays. Consider:

public static < T > T[] makeArray() {
T[] array = (T[]) new Object[5];
return array;

public static void main(String[] args) {
Integer[] ints = Test.< Integer >makeArray();

The assignment in `main` blows up with a `ClassCastException`. Using the [Eclipse]( debugger, the JVM thinks that the array is an `Object[]`. So the cast has basically been ignored. This is correct behaviour for Java’s arrays which you can never cast down anyway: `Integer[] ary = (Integer[]) new Object[] {1,2,3,4,5};` blows up with the same exception.

If you look at the `ArrayList` implementation you’ll see how they get around it. The array backing the list is never actually returned. Instead it is always copied. So now:

public static < T > T[] makeArray(T[] input, T… elems) {
T[] array = (T[]) new Object[elems.length];
System.arraycopy(elems, 0, array, 0, elems.length);
System.arraycopy(array, 0, input, 0,
Math.min(input.length, array.length));
return input;

public static void main(String[] args) {
Integer[] ints = Test.< Integer >makeArray(new Integer[0], 5, 4, 3, 2, 1);

This now works. However, were you trying to do this in a library, as I was, you may need to pass in a generic array which you can’t create which is the reason for the cast in the first place. Fun


Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>