2

suppose I have an arraylist of the form ArrayList<ArrayList<E>> ... what would be the most elegant way to convert this into 2 dimensional arrays

2 Answers 2

2

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);
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Yes ... but your code will be more efficient (and IMO more readable) if you cache the size values in final variables.
glowcoder,highly appreciated if you could post a complete example
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.