由于Java泛型的实现,你不能有这样的代码:

public class GenSet<E> {
    private E a[];

    public GenSet() {
        a = new E[INITIAL_ARRAY_LENGTH]; // error: generic array creation
    }
}

如何在保持类型安全的同时实现这一点?

我在Java论坛上看到一个解决方案是这样的:

import java.lang.reflect.Array;

class Stack<T> {
    public Stack(Class<T> clazz, int capacity) {
        array = (T[])Array.newInstance(clazz, capacity);
    }

    private final T[] array;
}

但我真的不明白这是怎么回事。


当前回答

如果你真的想包装一个固定大小的通用数组,你将有一个方法来添加数据到该数组,因此你可以正确地初始化数组,这样做:

import java.lang.reflect.Array;

class Stack<T> {
    private T[] array = null;
    private final int capacity = 10; // fixed or pass it in the constructor
    private int pos = 0;

    public void push(T value) {
        if (value == null)
            throw new IllegalArgumentException("Stack does not accept nulls");
        if (array == null)
            array = (T[]) Array.newInstance(value.getClass(), capacity);
        // put logic: e.g.
        if(pos == capacity)
             throw new IllegalStateException("push on full stack");
        array[pos++] = value;
    }

    public T pop() throws IllegalStateException {
        if (pos == 0)
            throw new IllegalStateException("pop on empty stack");
        return array[--pos];
    }
}

在这种情况下,您使用java.lang.reflect.Array.newInstance来创建数组,它将不是Object[],而是一个真正的T[]。 您不应该担心它不是最终的,因为它是在类中管理的。 注意,在push()上需要一个非空对象才能获得要使用的类型,因此我添加了一个对您所推送的数据的检查,并在那里抛出异常。

不过,这有点没有意义:通过push存储数据,方法的签名保证只有T个元素可以进入。所以数组是Object[]还是T[]或多或少是无关紧要的。

其他回答

我找到了一种快速简便的方法。注意,我只在Java JDK 8上使用了它。我不知道它是否能与以前的版本兼容。

虽然不能实例化特定类型参数的泛型数组,但可以将已经创建的数组传递给泛型类构造函数。

class GenArray <T> {
    private T theArray[]; // reference array

    // ...

    GenArray(T[] arr) {
        theArray = arr;
    }

    // Do whatever with the array...
}

现在在main中,我们可以像这样创建数组:

class GenArrayDemo {
    public static void main(String[] args) {
        int size = 10; // array size
        // Here we can instantiate the array of the type we want, say Character (no primitive types allowed in generics)
        Character[] ar = new Character[size];

        GenArray<Character> = new Character<>(ar); // create the generic Array

        // ...

    }
}

为了更灵活地使用数组,您可以使用链表。数组列表和在Java.util.ArrayList类中找到的其他方法。

您可以创建一个Object数组,并在所有位置将其强制转换为E。是的,这不是很干净的方法,但至少应该是可行的。

我必须反过来问一个问题:你的发电机组是“检查”还是“未检查”? 这是什么意思?

Checked: strong typing. GenSet knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E> argument, and methods will throw an exception when they are passed arguments that are not of type E. See Collections.checkedCollection. -> in that case, you should write: public class GenSet<E> { private E[] a; public GenSet(Class<E> c, int s) { // Use Array native method to create array // of a type only known at run time @SuppressWarnings("unchecked") final E[] a = (E[]) Array.newInstance(c, s); this.a = a; } E get(int i) { return a[i]; } } Unchecked: weak typing. No type checking is actually done on any of the objects passed as argument. -> in that case, you should write public class GenSet<E> { private Object[] a; public GenSet(int s) { a = new Object[s]; } E get(int i) { @SuppressWarnings("unchecked") final E e = (E) a[i]; return e; } } Note that the component type of the array should be the erasure of the type parameter: public class GenSet<E extends Foo> { // E has an upper bound of Foo private Foo[] a; // E erases to Foo, so use Foo[] public GenSet(int s) { a = new Foo[s]; } ... }

所有这些都是由于Java中泛型的一个已知且刻意的弱点:它是使用擦除来实现的,因此“泛型”类不知道它们在运行时是用什么类型参数创建的,因此不能提供类型安全,除非实现了一些显式机制(类型检查)。

在Java 8中,我们可以使用lambda或方法引用创建一种泛型数组。这类似于反射方法(传递一个类),但这里我们没有使用反射。

@FunctionalInterface
interface ArraySupplier<E> {
    E[] get(int length);
}

class GenericSet<E> {
    private final ArraySupplier<E> supplier;
    private E[] array;

    GenericSet(ArraySupplier<E> supplier) {
        this.supplier = supplier;
        this.array    = supplier.get(10);
    }

    public static void main(String[] args) {
        GenericSet<String> ofString =
            new GenericSet<>(String[]::new);
        GenericSet<Double> ofDouble =
            new GenericSet<>(Double[]::new);
    }
}

例如,<A> A[] Stream.toArray(IntFunction<A[]>)使用此方法。

这也可以在java 8之前使用匿名类来完成,但是比较麻烦。

我找到了一个解决这个问题的方法。

下面这行代码抛出泛型数组创建错误

List<Person>[] personLists=new ArrayList<Person>()[10];

但是,如果我将List<Person>封装在一个单独的类中,它就可以工作。

import java.util.ArrayList;
import java.util.List;


public class PersonList {

    List<Person> people;

    public PersonList()
    {
        people=new ArrayList<Person>();
    }
}

您可以通过getter在PersonList类中公开人员。下面的行将给出一个数组,每个元素中都有List<Person>。也就是说数组List<Person>。

PersonList[] personLists=new PersonList[10];

我需要这样的东西在一些代码中,我正在工作,这就是我所做的让它工作。到目前为止还没有问题。