3 回答
TA贡献1909条经验 获得超7个赞
像这样:
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()]);
TA贡献1803条经验 获得超3个赞
它实际上并不需要返回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);
}
}
TA贡献1817条经验 获得超14个赞
我得到了答案...这似乎工作得很好
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;
}
添加回答
举报