如何在Java中建立通用數組?

因爲Java泛型的實現,所以不能有如下代碼: html

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

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

如何在保持類型安全的同時實現此目的? java

我在Java論壇上看到了這樣的解決方案: api

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;
}

可是我真的不知道發生了什麼。 數組


#1樓

一個簡單但雜亂的解決方法是在主類中嵌套第二個「 holder」類,並使用它來保存數據。 安全

public class Whatever<Thing>{
    private class Holder<OtherThing>{
        OtherThing thing;
    }
    public Holder<Thing>[] arrayOfHolders = new Holder<Thing>[10]
}

#2樓

我編寫了此代碼段,以反射方式實例化爲簡單的自動化測試實用程序傳遞的類。 oracle

Object attributeValue = null;
try {
    if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }
    else if(!clazz.isInterface()){
        attributeValue = BeanUtils.instantiateClass(clazz);
    }
} catch (Exception e) {
    logger.debug("Cannot instanciate \"{}\"", new Object[]{clazz});
}

請注意如下部分: 測試

if(clazz.isArray()){
        Class<?> arrayType = clazz.getComponentType();
        attributeValue = Array.newInstance(arrayType, 0);
    }

用於數組初始化,其中Array.newInstance(array的類,array的大小) 。 類能夠是原始(int.class)和對象(Integer.class)。 spa

BeanUtils是Spring的一部分。 debug


#3樓

還要看這段代碼: code

public static <T> T[] toArray(final List<T> obj) {
    if (obj == null || obj.isEmpty()) {
        return null;
    }
    final T t = obj.get(0);
    final T[] res = (T[]) Array.newInstance(t.getClass(), obj.size());
    for (int i = 0; i < obj.size(); i++) {
        res[i] = obj.get(i);
    }
    return res;
}

它將任何類型的對象的列表轉換爲相同類型的數組。


#4樓

要擴展更多維度,只需將[]和維度參數添加到newInstance()T是類型參數, clsClass<T>d1d5是整數):

T[] array = (T[])Array.newInstance(cls, d1);
T[][] array = (T[][])Array.newInstance(cls, d1, d2);
T[][][] array = (T[][][])Array.newInstance(cls, d1, d2, d3);
T[][][][] array = (T[][][][])Array.newInstance(cls, d1, d2, d3, d4);
T[][][][][] array = (T[][][][][])Array.newInstance(cls, d1, d2, d3, d4, d5);

有關詳細信息,請參見Array.newInstance()


#5樓

也許與這個問題無關,可是當我使用時出現「 generic array creation 」錯誤

Tuple<Long,String>[] tupleArray = new Tuple<Long,String>[10];

我發現@SuppressWarnings({"unchecked"})的如下做品(併爲我工做@SuppressWarnings({"unchecked"})

Tuple<Long, String>[] tupleArray = new Tuple[10];
相關文章
相關標籤/搜索