所以,通常ArrayList.toArray()
会返回Object[]
的类型....但是假设它是一个
对象Arraylist
的{{1}},如何让Custom
返回toArray()
而非Custom[]
的类型?
答案 0 :(得分:276)
像这样:
List<String> list = new ArrayList<String>();
String[] a = list.toArray(new String[0]);
在Java6之前,建议写:
String[] a = list.toArray(new String[list.size()]);
因为内部实现无论如何都会重新分配一个大小合适的数组,所以你最好先做好。从Java6开始,首选空数组,请参阅.toArray(new MyClass[0]) or .toArray(new MyClass[myList.size()])?
如果您的列表输入不正确,则需要在调用toArray之前进行强制转换。像这样:
List l = new ArrayList<String>();
String[] a = ((List<String>)l).toArray(new String[l.size()]);
答案 1 :(得分:13)
它实际上不需要返回Object[]
,例如: -
List<Custom> list = new ArrayList<Custom>();
list.add(new Custom(1));
list.add(new Custom(2));
Custom[] customs = new Custom[list.size()];
list.toArray(customs);
for (Custom custom : customs) {
System.out.println(custom);
}
这是我的Custom
课程: -
public class Custom {
private int i;
public Custom(int i) {
this.i = i;
}
@Override
public String toString() {
return String.valueOf(i);
}
}
答案 2 :(得分:5)
arrayList.toArray(new Custom[0]);
答案 3 :(得分:3)
将List转换为特定类型的Array(例如Long)的较短版本:
Long[] myArray = myList.toArray(Long[]::new);
答案 4 :(得分:0)
我得到了答案......这似乎工作得很好
public int[] test ( int[]b )
{
ArrayList<Integer> l = new ArrayList<Integer>();
Object[] returnArrayObject = l.toArray();
int returnArray[] = new int[returnArrayObject.length];
for (int i = 0; i < returnArrayObject.length; i++){
returnArray[i] = (Integer) returnArrayObject[i];
}
return returnArray;
}
答案 5 :(得分:0)
@SuppressWarnings("unchecked")
public static <E> E[] arrayListToArray(ArrayList<E> list)
{
int s;
if(list == null || (s = list.size())<1)
return null;
E[] temp;
E typeHelper = list.get(0);
try
{
Object o = Array.newInstance(typeHelper.getClass(), s);
temp = (E[]) o;
for (int i = 0; i < list.size(); i++)
Array.set(temp, i, list.get(i));
}
catch (Exception e)
{return null;}
return temp;
}
样品:
String[] s = arrayListToArray(stringList);
Long[] l = arrayListToArray(longList);