因此,通常ArrayList.toArray()将返回Object[]....的类型但是假设它是 对象自定义的数组列表,我如何使toArray()返回自定义[]而不是对象[]的类型?


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);
    }
}

是这样的:

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()]);

我有答案了…这似乎工作得非常好

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;
}

 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;
  }

将List转换为特定类型的Array(例如Long)的简短版本:

Long[] myArray = myList.toArray(Long[]::new);

(可由java11提供)