我想將4個字符串列表存儲到索引0-3內的一個數組,並且能夠檢查索引是否填滿(!= null)。初始化列表數組<String>對象
出於這個原因,我需要初始化類型列表數組,從而未能在Eclipse中的消息「無法創建列表的通用陣列」:
// Does not work
List<String>[] myArray = new List<String>[4];
// Does not work
List<String>[] myArray = new ArrayList<String>[4];
做它像推動在Convert an ArrayList to an object array:
ArrayList<List<String>> myArrayList = new ArrayList<List<String>>();
myArrayList.add(new ArrayList<String>());
myArrayList.add(new ArrayList<String>());
myArrayList.add(new ArrayList<String>());
myArrayList.add(new ArrayList<String>());
// Does not work
List<String>[] myArray = myArrayList.toArray(new List<String>[myArrayList.size()]);
// Does not work
List<String>[] myArray = myArrayList.toArray(new ArrayList<String [myArrayList.size()]);
但爲什麼這不起作用?
可能重複(http://stackoverflow.com/questions/10227201/initialize-an-array-of-arraylist) –
因爲「你不能在Java中創建一個通用數組」。這是一個設計選擇,它與數組類型的可重構性與泛型類型參數的不可重構性之間的不匹配有關。 –
只Cuck Norris可以啓動接口:新列表 [myArrayList.size()] !!! :-) –