[英]How do I create a new AnyType array
I am using the code from the answer How do I create a new AnyType[] array? 我正在使用答案中的代码。 如何创建新的AnyType []数组? . 。 My question is how to initialize this array. 我的问题是如何初始化此数组。 When I try to run this code, I get a null pointer exception on Clear(), which I think is due to using theItems.getClass since theItems haven't been declared already. 当我尝试运行此代码时,我在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++;
}
}
So I found two ways I could accomplish this. 因此,我找到了两种方法可以实现此目的。 The first, using Jack's comment from above, looks like: 第一个,使用上面杰克的注释,看起来像:
public static <T> T[] alloc(int length, T ... base) {
return Arrays.copyOf( base, length );
}
It can then be called like: 然后可以这样称呼它:
theItems = ClassName.alloc(DEFAULT_CAPACITY);
The way I ended up using could be used because I implemented comparable: 可以使用我最终使用的方法,因为我实现了可比性:
theItems = (AnyType []) new Comparable[ DEFAULT_CAPACITY ];
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.