使arrayList.toArray()返回更具体的types

所以,通常ArrayList.toArray()会返回一个types的Object[] ….但假设它是一个对象CustomArraylist ,我如何使toArray()返回一个Custom[]types而不是Object[]

喜欢这个:

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

这样做很诱人:

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

但内部实现将重新分配一个大小适中的数组,所以你最好先做。

如果你的列表没有正确input,你需要在调用toArray之前进行强制转换。 喜欢这个:

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

它并不需要返回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); } } 

我得到了答案…这似乎工作得很好

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

样品:

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