Java’s broken generics

July 18th, 2005 matthew

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

Entry Filed under: Technology

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed

Calendar

July 2005
M T W T F S S
    Aug »
 123
45678910
11121314151617
18192021222324
25262728293031

Most Recent Posts