通常情况下,ArrayList.toArray()
的返回类型是 Object[]
。但如果这个 ArrayList
是由对象 Custom
组成的,我该如何使 toArray()
返回类型为 Custom[]
而不是 Object[]
呢?
通常情况下,ArrayList.toArray()
的返回类型是 Object[]
。但如果这个 ArrayList
是由对象 Custom
组成的,我该如何使 toArray()
返回类型为 Custom[]
而不是 Object[]
呢?
像这样:
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])或.toArray(new MyClass [myList.size()])?
如果列表类型不正确,则需要在调用toArray之前进行强制转换。像这样:
List l = new ArrayList<String>();
String[] a = ((List<String>)l).toArray(new String[l.size()]);
.toArray(new String[]{})
。 - arnonuem将List转换为特定类型(例如Long)的数组的简化版本:
Long[] myArray = myList.toArray(Long[]::new);
(自Java 11起可用)
它实际上不一定需要返回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);
}
}
arrayList.toArray(new Custom[0]);
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;
}