[英]How do I create a new AnyType array
我正在使用答案中的代碼。 如何創建新的AnyType []數組? 。 我的問題是如何初始化此數組。 當我嘗試運行此代碼時,我在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++;
}
}
因此,我找到了兩種方法可以實現此目的。 第一個,使用上面傑克的注釋,看起來像:
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 ];
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.