1

I have the following code in Java:

public static<T> void doIt(Class<T> t)
{
    T[] arr;
    arr = (T[])Array.newInstance(t, 4);
}

I want to be able to use doIt using both primitive type such as double and using class objects such as String.

I could do it by using (code compiles):

    doIt(double.class);
    doIt(String.class);

However, I am worried that in the first case, the Java compiler will actually wrap the double primitive type using a Double class, which I don't want. I actually want it to instantiate a primitive array in this case (while instantiating an objects array with the String case). Does someone know what happens with doIt(double.class)? Is it instantiated as Double or double?

Thanks.

kloop
  • 3,979
  • 11
  • 39
  • 58

4 Answers4

4

You couldn't actually make T = double here - Java generics simply don't work with primitive types. However, you can still instantiate your array:

import java.lang.reflect.*;

public class Test {
    public static void main(String[] args) {
        createArray(double.class);
    }

    private static void createArray(Class<?> clazz) {
        Object array = Array.newInstance(clazz, 4);
        System.out.println(array.getClass() == double[].class); // true
    }
}

It really depends on what you want to do with the array afterwards.

Jon Skeet
  • 1,335,956
  • 823
  • 8,931
  • 9,049
  • +1 on the "what you want to do with the array afterwards", which is the critical question. `Array.newInstance` can create primitive arrays fine; but cannot be returned as type `T[]`. I assume that the OP wants to return it from the function as type `T[]`, which would fail – newacct Nov 18 '11 at 03:08
1

You can make an array of primitive double like this:

double[] arr = (double[]) Array.newInstance(double.class, 0);

But you can't make this work with generics, because generic parameters are always reference types, not primitive types.

erickson
  • 257,800
  • 54
  • 385
  • 479
0

Generics will work with objects so it should be a Double after boxing.

Udo Held
  • 11,937
  • 11
  • 67
  • 90
0

You can create a method that takes an array type instead of the element type and get around the problem that type parameters must be reference types since all array types are reference types.

<T> T doIt(Class<T> arrayType) {
  assert arrayType.getElementType() != null;
  return <T> Array.newInstance(arrayType.getElementType(), 4);
}
Mike Samuel
  • 114,030
  • 30
  • 209
  • 240