猿问

使arrayList.toArray()返回更多特定类型

因此,通常ArrayList.toArray()会返回一种Object[]....,但假设它是一个 Arraylistobject对象Custom,我如何使它toArray()返回Custom[]而不是类型Object[]



莫回无
浏览 916回答 3
3回答

jeck猫

像这样: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之前进行强制类型转换。像这样:&nbsp; &nbsp; List l = new ArrayList<String>();&nbsp; &nbsp; String[] a = ((List<String>)l).toArray(new String[l.size()]);

繁星点点滴滴

它实际上并不需要返回Object[],例如:&nbsp; &nbsp; List<Custom> list = new ArrayList<Custom>();&nbsp; &nbsp; list.add(new Custom(1));&nbsp; &nbsp; list.add(new Custom(2));&nbsp; &nbsp; Custom[] customs = new Custom[list.size()];&nbsp; &nbsp; list.toArray(customs);&nbsp; &nbsp; for (Custom custom : customs) {&nbsp; &nbsp; &nbsp; &nbsp; System.out.println(custom);&nbsp; &nbsp; }这是我的Custom课:public class Custom {&nbsp; &nbsp; private int i;&nbsp; &nbsp; public Custom(int i) {&nbsp; &nbsp; &nbsp; &nbsp; this.i = i;&nbsp; &nbsp; }&nbsp; &nbsp; @Override&nbsp; &nbsp; public String toString() {&nbsp; &nbsp; &nbsp; &nbsp; return String.valueOf(i);&nbsp; &nbsp; }}

大话西游666

我得到了答案...这似乎工作得很好public int[] test ( int[]b ){&nbsp; &nbsp; ArrayList<Integer> l = new ArrayList<Integer>();&nbsp; &nbsp; Object[] returnArrayObject = l.toArray();&nbsp; &nbsp; int returnArray[] = new int[returnArrayObject.length];&nbsp; &nbsp; for (int i = 0; i < returnArrayObject.length; i++){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;returnArray[i] = (Integer)&nbsp; returnArrayObject[i];&nbsp; &nbsp; }&nbsp; &nbsp; return returnArray;}
随时随地看视频慕课网APP

相关分类

Java
我要回答