views:

111

answers:

2
import java.lang.reflect.Array;

public class PrimitiveArrayGeneric {
    static <T> T[] genericArrayNewInstance(Class<T> componentType) {
        return (T[]) Array.newInstance(componentType, 0);
    }

    public static void main(String args[]) {
        int[] intArray;
        Integer[] integerArray;

        intArray = (int[]) Array.newInstance(int.class, 0);
        // Okay!

        integerArray = genericArrayNewInstance(Integer.class);
        // Okay!

        intArray = genericArrayNewInstance(int.class);
        // Compile time error:
           // cannot convert from Integer[] to int[]

        integerArray = genericArrayNewInstance(int.class);
        // Run time error:
           // ClassCastException: [I cannot be cast to [Ljava.lang.Object;
    }    
}

I'm trying to fully understand how generics works in Java. Things get a bit weird for me in the 3rd assignment in the above snippet: the compiler is complaining that Integer[] cannot be converted to int[]. The statement is 100% true, of course, but I'm wondering WHY the compiler is making this complaint.

If you comment that line, and follow the compiler's "suggestion" as in the 4th assignment, the compiler is actually satisfied!!! NOW the code compiles just fine! Which is crazy, of course, since like the run time behavior suggests, int[] cannot be converted to Object[] (which is what T[] is type-erased into at run time).

So my question is: why is the compiler "suggesting" that I assign to Integer[] instead for the 3rd assignment? How does the compiler reason to arrive to that (erroneous!) conclusion?


There is a lot of confusion in the two answers so far, so I created another baffling example to illustrate the underlying issue here:

public class PrimitiveClassGeneric {    
    static <T extends Number> T test(Class<T> c) {
        System.out.println(c.getName() + " extends " + c.getSuperclass());
        return (T) null;
    }
    public static void main(String args[]) {
        test(Integer.class);
        // "java.lang.Integer extends class java.lang.Number"

        test(int.class);
        // "int extends null"
    }
}

Am I the only one that thinks it's absolutely crazy that the compiler lets the above code compiles?

It wouldn't be unreasonable to print c.getSuperclass().getName() in the above code, for example, since I specified that T extends Number. Of course now getName() will throw NullPointerException when c == int.class, since c.getSuperclass() == null.

And to me, that's a very good reason to reject the code from compiling in the first place.


Perhaps the ultimate craziness:

    int.class.cast(null);

That code compiles AND runs fine.

+4  A: 

The type of int.class is Class<Integer>, so genericArrayNewInstance() would be inferred to return a Integer[]. But the function actually creates an int[], so it would have a class cast exception when it is returned. Basically, the cast to T[] inside the function is not legitimate in this case, because int[] is not a T[] (primitives can't be used in type variables). You cannot handle primitive array types generically; so you either have to have your method just return type Object, or you have to make separate methods for reference types and for primitive types.

newacct
I could be wrong but I think that technically `int` doesn't have a class but when you use `int.class` the compiler boxes `int` to `Integer`
matt b
@matt-b, int.class is a _real_ Class. Check the javadoc for Class.isPrimitive. It's been around since 1.1. Well before boxing. Integer.class != int.class. Integer.TYPE == int.class.
nicerobot
"The type of `int.class` is `Class<Integer>`" -- I think herein lies the key
polygenelubricants
+3  A: 

A few points:

  1. primitives are autoboxed to their object counterparts (wrappers) when needed
  2. primitive arrays are objects, so they are not autoboxed.
  3. generics cannot use primitives as type parameters

For your examples, here are my assumptions:

in 3 the autoboxing happens to the type parameter, but doesn't happen to the returned array
in 4 the autoboxing happens to the type parameter, but doesn't happen to the method argument, so in fact an int[] is generated, but Integer[] is expected

Autoboxing in the case of type parameter might not be exactly autoboxing, but is something with the same idea.

Update: your 2nd example has nothing wrong. int.class is a Class, so the compiler has no reason to reject it.

Bozho
These are all good points but they don't answer my question. Also, there is no autoboxing in my example. If you print `componentType` in `genericArrayNewInstance`, it prints the passed `.class` objects as it should.
polygenelubricants
@polygenelubricants that's what I said - autoboxing doesn't happen to the method argumente - it has happened (well, it might not be exactly autoboxing, but something with similar idea) to the type parameter. The type parameter _cannot_ be primitive, hence the wrapper is used.
Bozho
"your 2nd example has nothing wrong" -- but my generic type specification mandates that `T extends Number`, where as `int.class extends null`. See also update to Q.
polygenelubricants
that fits exactly in my explanation about autoboxing type parameters but not autoboxing the method arguments. I still don't see a problem.
Bozho