当我尝试使用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