因此,通常ArrayList.toArray()将返回Object[]....的类型但是假设它是 对象自定义的数组列表,我如何使toArray()返回自定义[]而不是对象[]的类型?
当前回答
我有答案了…这似乎工作得非常好
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;
}
其他回答
将List转换为特定类型的Array(例如Long)的简短版本:
Long[] myArray = myList.toArray(Long[]::new);
(可由java11提供)
public static <E> E[] arrayListToTypedArray(List<E> list) {
if (list == null) {
return null;
}
int noItems = list.size();
if (noItems == 0) {
return null;
}
E[] listAsTypedArray;
E typeHelper = list.get(0);
try {
Object o = Array.newInstance(typeHelper.getClass(), noItems);
listAsTypedArray = (E[]) o;
for (int i = 0; i < noItems; i++) {
Array.set(listAsTypedArray, i, list.get(i));
}
} catch (Exception e) {
return null;
}
return listAsTypedArray;
}
我有答案了…这似乎工作得非常好
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;
}
arrayList.toArray(new Custom[0]);
http://download.oracle.com/javase/7/docs/api/java/util/ArrayList.html#toArray%28java.lang.Object[]%29
它并不真的需要返回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);
}
这是我的自定义类:-
public class Custom {
private int i;
public Custom(int i) {
this.i = i;
}
@Override
public String toString() {
return String.valueOf(i);
}
}