3

我正在使用通用方法进行一些测试,我想将下面的这两种方法(convertFloatListToArray 和 convertShortListToArray)转换为一个(convertListToArray):

public class Helper{
    public static float[] convertFloatListToArray(List<Float> list){
        float[] array = new float[list.size()];

        for(int i = 0; i<list.size(); i++){
            array[i] = list.get(i);
        }

        return array;
    }

    public static short[] convertShortListToArray(List<Short> list){
        short[] array = new short[list.size()];

        for(int i = 0; i<list.size(); i++){
            array[i] = list.get(i);
        }

        return array;
    }
}

但是当我尝试使用泛型时,如下所示,我有一些错误:

public class Helper{
    public static <T, E> T convertListToArray(List<E> list){
        T array = new T[list.size()];

        for(int i = 0; i<list.size(); i++){
            array[i] = list.get(i);
        }

        return array;
    }
}

我可以理解关于泛型的 Java 限制,但我想知道是否有人知道我没有看到的使用泛型方法的任何解决方案。

4

1 回答 1

9

从当前版本 (Java 12) 开始,原始类型无法用 Java 泛型表示。更具体地说,我们不能提供原始类型作为类型参数。(我们不能做例如Foo<int>。)我们也不能使用类型变量作为new表达式中的类型,所以我们不能做new T[n]一个数组。因此,没有理想的方法来做到这一点。

可以使用一些反射 ( ) 合理地做到这一点,java.lang.reflect.Array我们需要提供 aClass作为参数。这是如何完成的示例:

/**
 * Unboxes a List in to a primitive array.
 *
 * @param  list      the List to convert to a primitive array
 * @param  arrayType the primitive array type to convert to
 * @param  <P>       the primitive array type to convert to
 * @return an array of P with the elements of the specified List
 * @throws NullPointerException
 *         if either of the arguments are null, or if any of the elements
 *         of the List are null
 * @throws IllegalArgumentException
 *         if the specified Class does not represent an array type, if
 *         the component type of the specified Class is not a primitive
 *         type, or if the elements of the specified List can not be
 *         stored in an array of type P
 */
public static <P> P toPrimitiveArray(List<?> list, Class<P> arrayType) {
    if (!arrayType.isArray()) {
        throw new IllegalArgumentException(arrayType.toString());
    }
    Class<?> primitiveType = arrayType.getComponentType();
    if (!primitiveType.isPrimitive()) {
        throw new IllegalArgumentException(primitiveType.toString());
    }

    P array = arrayType.cast(Array.newInstance(primitiveType, list.size()));

    for (int i = 0; i < list.size(); i++) {
        Array.set(array, i, list.get(i));
    }

    return array;
}

示例调用:

List<Integer> list = List.of(1, 2, 3);
int[] ints = toPrimitiveArray(list, int[].class);

请注意,这Array.set将执行扩大的原始转换,因此以下工作:

List<Integer> list = List.of(1, 2, 3);
double[] doubles = toPrimitiveArray(list, double[].class);

但它不会执行缩小转换,因此以下会引发异常:

List<Integer> list = List.of(1, 2, 3);
byte[] bytes = toPrimitiveArray(list, byte[].class); // throws

如果您愿意,也可以使用该代码使复制更容易:

public static int[] toIntArray(List<Integer> list) {
    return toPrimitiveArray(list, int[].class);
}
public static double[] toDoubleArray(List<Double> list) {
    return toPrimitiveArray(list, double[].class);
}
...

(不过,拥有多个这样的方法并不是真正的通用方法。)


您有时会看到地点的一种解决方案如下所示:

public static <P> P toPrimitiveArray(List<?> list) {
    Object obj0 = list.get(0);
    Class<?> type;
    // "unbox" the Class of obj0
    if (obj0 instanceof Integer)
        type = int.class;
    else if (obj0 instanceof Double)
        type = double.class;
    else if (...)
        type = ...;
    else
        throw new IllegalArgumentException();

    Object array = Array.newInstance(type, list.size());

    for (int i = 0; i < list.size(); i++) {
        Array.set(array, i, list.get(i));
    }

    return (P) array;
}

但是,这样做存在各种问题:

  • 如果列表为空,我们不知道要创建什么类型的数组。
  • 如果列表中有不止一种类型的对象,则不起作用。
  • 未经检查地将结果数组强制转换为P,因此存在堆污染的危险。

Class将 a作为参数传入要好得多。


此外,虽然可以编写许多拆箱数组的重载:

public static int[]    unbox(Integer[] arr) {...}
public static long[]   unbox(Long[]    arr) {...}
public static double[] unbox(Double[]  arr) {...}
...

由于类型擦除的影响,不可能编写拆箱许多不同类型的重载,List如下所示:

public static int[]    unbox(List<Integer> list) {...}
public static long[]   unbox(List<Long>    list) {...}
public static double[] unbox(List<Double>  list) {...}
...

那不会编译,因为我们不允许在同一个类中有多个具有相同名称和擦除的方法。这些方法必须有不同的名称。


作为旁注,这里有一些非通用的解决方案:

  • 从 Java 8 开始,我们可以取消装箱,List并使用API :IntegerLongDoubleStream

    List<Long> list = List.of(1L, 2L, 3L);
    long[] longs = list.stream().mapToLong(Long::longValue).toArray();
    
  • Google GuavaCollection在他们的类中有拆箱方法com.google.common.primitives,例如Doubles.toArray

    List<Double> list = List.of(1.0, 2.0, 3.0);
    double[] doubles = Doubles.toArray(list);
    
于 2014-08-05T23:11:30.913 回答