关于java:make arrayList.toArray()返回更具体的类型

make arrayList.toArray() return more specific types

所以,通常情况下,ArrayList.toArray()会返回Object[]的类型……但假设它是对象CustomArraylist如何使toArray()返回Custom[]类型而不是Object[]类型?


这样的:

1
2
3
List<String> list = new ArrayList<String>();

String[] a = list.toArray(new String[0]);

这是写在java6建议:

1
String[] a = list.toArray(new String[list.size()]);

因为我们在内部实现这样大小的数组a realloc无论如何做它为你更好。这是首选的,因为java6空数组,湖.toarray(new MyClass [ 0 ])或.toarray(new MyClass mylist.size)[(])?

如果你的列表是不恰当的A型铸造之前你需要做电话拷贝。这样的:

1
2
3
    List l = new ArrayList<String>();

    String[] a = ((List<String>)l).toArray(new String[l.size()]);


它并不真的需要Object[]回报,例如:

1
2
3
4
5
6
7
8
9
10
    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类:

1
2
3
4
5
6
7
8
9
10
11
12
public class Custom {
    private int i;

    public Custom(int i) {
        this.i = i;
    }

    @Override
    public String toString() {
        return String.valueOf(i);
    }
}


1
arrayList.toArray(new Custom[0]);

download.oracle.com http:/ / / / /文档/ 7 JavaSE util / / / Java的API arraylist.html # % % [ 29 ] 28java.lang.object拷贝


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
@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;
    }

样本:

1
2
String[] s = arrayListToArray(stringList);
Long[]   l = arrayListToArray(longList);


我得到的答案...this似乎工作非常精细

1
2
3
4
5
6
7
8
9
10
11
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;
}