如何创建通用的基本数组? [英] How to create generic primitive arrays?

查看:127
本文介绍了如何创建通用的基本数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从两种方法来创建通用数组a以下问题

使用给出了两种方法,

@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?

推荐答案

试试这个

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

final int[] primitiveArray3 = array3(int[].class, 0);

这篇关于如何创建通用的基本数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆