當我嘗試使用Arrays.asList(myArray)
從數組創建ArrayList myArrayList
時,我沒有收到myArray
中元素的List
。相反,我得到Array
的清單。Java Array and ArrayList
myArrayList
的大小是1。當我嘗試做myArrayList.toArray()
時,我得到了一個二維數組。如何在列表中獲取myArray
的元素?迭代唯一的選擇?
當我嘗試使用Arrays.asList(myArray)
從數組創建ArrayList myArrayList
時,我沒有收到myArray
中元素的List
。相反,我得到Array
的清單。Java Array and ArrayList
myArrayList
的大小是1。當我嘗試做myArrayList.toArray()
時,我得到了一個二維數組。如何在列表中獲取myArray
的元素?迭代唯一的選擇?
您可以通過不同的方式實現它。 3 example of converting array to arraylist and arraylist to array in java可能會有所幫助。
嘗試在方法調用中提供泛型類型。以下給出了2個String元素的列表。
String[] strings = new String[]{"1", "2"};
List<String> list = Arrays.<String>asList(strings);
System.out.println(list.size());
這項工作?
Object[] myArray = new Object[4]; //change this to whatever object you have
ArrayList<Object> list = new ArrayList<Object>();
for (Object thing : myArray) list.add(thing);
首先,asList方法是正確的方法:
Integer[] myArray = new Integer[3];
List<Integer> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 3, as expected
的問題可能是你所呼叫的可變參數asList方法以這樣的方式,Java是解釋您的參數作爲第一個可變參數值(而不是作爲值的數組)。
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList(myArray);
System.out.println(myArrayList.size()); // prints 1 - java invoked it as an array of Integer[]
要解決此問題,請您鑄造參數作爲Object[]
迫使可變參數調用,如:
Object myArray = new Integer[3];
List<Object> myArrayList = Arrays.asList((Object[]) myArray); // Note cast here
System.out.println(myArrayList.size()); // prints 3, as desired
看起來像你的'myArray'是一個二維數組。你有沒有確定沒有像{{「one」,「two」}}'這樣的雙括號? – adarshr
@bluish對不起,我沒有那樣做。我會糾正自己。謝謝。 @其他人就像Banther所說的那樣,我正在用int []來嘗試它。下一次,我會嘗試發佈代碼片段。謝謝 – Suma