make arrayList.toArray() return more specific types
所以,通常情况下,
这样的:
这是写在java6建议:
因为我们在内部实现这样大小的数组a realloc无论如何做它为你更好。这是首选的,因为java6空数组,湖.toarray(new MyClass [ 0 ])或.toarray(new MyClass mylist.size)[(])?
如果你的列表是不恰当的A型铸造之前你需要做电话拷贝。这样的:
它并不真的需要
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); } |
这里是我的
1 2 3 4 5 6 7 8 9 10 11 12 |
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; } |
样本:
我得到的答案...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; } |