converting double arraylist to 2 dimensional arrays in java
suppose I have an arraylist of the form ArrayList<Arr开发者_StackOverflow社区ayList<E>>
... what would be the most elegant way to convert this into 2 dimensional arrays
This assumes you don't have any nulls or anything tricky like that. This also doesn't make any guarantees about the uniformity of the array (i.e. being "rectangular")
final int listSize = list.size();
E[][] darr = new E[listSize][];
for(int i = 0; i < listSize; i++) {
ArrayList<E> sublist = list.get(i);
final int sublistSize = sublist.size();
darr[i] = new E[sublistSize];
for(int j = 0; j < sublistSize; j++) {
darr[i][j] = sublist.get(j);
}
}
If E
is a generic class, we have the problem that one can't create generic arrays without reflection, and with Reflection we need the class object (or an example array object).
I'm not sure this is "elegant", but let's try:
import java.lang.reflect.Array;
<E> public static E[][] toArray(List<List<E>> list, Class<E> elementType) {
E[] sample = (E[])Array.newInstance(elementType, 0);
List<E[]> tempList = new ArrayList<E[]>(list.size());
for(List<E> subList : list) {
tempList.add( subList.toArray(sample));
}
E[][] finalSample = (E[][])Array.newInstance(sample.getClass(), 0)
return tempList.toArray(finalSample);
}
This may need some @SuppressWarning("unchecked")
for the casts from Array.newInstance.
精彩评论