3

This is a following question coming from Two methods for creating generic arrays.

With given two methods,

@SuppressWarnings("unchecked")
static <T> T[] array1(final Class<T> elementType, final int size) {

    return (T[]) Array.newInstance(elementType, size);
}
static <T> T[] array2(final Class<T[]> arrayType, final int size) {

    return arrayType.cast(Array.newInstance(arrayType.getComponentType(), size));
}

Both methods work fine for Object type.

final Integer[] objectArray1 = array1(Integer.class, 0);
final Integer[] objectArray2 = array2(Integer[].class, 0);

When it comes to primitives, both invocation don't compile.

// array1
final int[] primitiveArray1 = array1(int.class, 0);
GenericArray.java:12: error: incompatible types
        final int[] primitiveArray1 = array1(int.class, 0);
                                            ^
  required: int[]
  found:    Integer[]
1 error
// array2
final int[] primitiveArray2 = array2(int[].class, 0);
GenericArray.java:13: error: method array2 in class GenericArray cannot be applied to given types;
        final int[] primitiveArray2 = array2(int[].class, 0);
                                      ^
  required: Class<T[]>,int
  found: Class<int[]>,int
  reason: inferred type does not conform to declared bound(s)
    inferred: int
    bound(s): Object
  where T is a type-variable:
    T extends Object declared in method <T>array2(Class<T[]>,int)
1 error

How can I do with primitive types?

Community
  • 1
  • 1
Jin Kwon
  • 17,188
  • 11
  • 87
  • 147

6 Answers6

4

Primitives are incompatible with generics; for example, you can't create a List<int>, and the type of int.class is Class<Integer> rather than Class<int>. So what you describe is not possible.

ruakh
  • 156,364
  • 23
  • 244
  • 282
4

Try this instead

static <A> A array3(final Class<A> arrayType, final int size) 
{    impl omitted... }

final int[] primitiveArray3 = array3(int[].class, 0);
ZhongYu
  • 18,232
  • 5
  • 28
  • 55
1

This is the normal way:

int[] foo = (int[])Array.newInstance(int.class, 5);

As ruakh mentioned, you cannot make something work generically for primitive types, so you're gonna have to cast the result somehow.

newacct
  • 110,405
  • 27
  • 152
  • 217
0

You cannot use primitives with generics. On the other hand, you can use Integer[] in place of int[] and rely on auto(un)boxing to convert between int and Integer when necessary.

Code-Apprentice
  • 69,701
  • 17
  • 115
  • 226
0

You cannot use primitives with generics, only Objects; however, you can use their wrappers: Integer, Character, etc.

Steve P.
  • 13,674
  • 6
  • 38
  • 67
0

This works and creates int[]:

final Object instance = Array.newInstance(Integer.TYPE, 0);
Eugene
  • 8,611
  • 2
  • 26
  • 28