我正在使用答案How do I create a new AnyType[] array?中的代码。我的问题是如何初始化这个数组。当我试图运行这段代码时,会在Clear()上得到一个空指针异常,我认为这是由于使用了theItems.getClass,因为theItems还没有被声明。
public class Whatever<AnyType extends Comparable<? super AnyType>> extends AbstractCollection<AnyType> implements List<AnyType> {
private static final int DEFAULT_CAPACITY = 10;
private static final int NOT_FOUND = -1;
private AnyType[] theItems;
private int theSize;
private int modCount = 0;
public Whatever() {
clear();
}
/**
* Change the size of this collection to zero.
*/
public void clear() {
theSize = 0;
theItems = (AnyType[]) java.lang.reflect.Array.newInstance(theItems.getClass().getComponentType(), DEFAULT_CAPACITY);
modCount++;
}
}发布于 2016-03-12 21:00:13
所以我找到了两种方法来完成这个任务。第一条,使用Jack上面的评论,看起来如下:
public static <T> T[] alloc(int length, T ... base) {
return Arrays.copyOf( base, length );
}然后,它可以被称为:
theItems = ClassName.alloc(DEFAULT_CAPACITY);可以使用我最终使用的方式,因为我实现了可比较的:
theItems = (AnyType []) new Comparable[ DEFAULT_CAPACITY ];https://stackoverflow.com/questions/35953498
复制相似问题