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;
}
I got the answer...this seems to be working perfectly fine
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;
}
arrayList.toArray(new Custom[0]);
It doesn't really need to return Object[]
, for example:-
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);
}
Here's my Custom
class:-
public class Custom {
private int i;
public Custom(int i) {
this.i = i;
}
@Override
public String toString() {
return String.valueOf(i);
}
}
A shorter version of converting List to Array of specific type (for example Long):
Long[] myArray = myList.toArray(Long[]::new);
Source: Stackoverflow.com