I was working through getting myself past the creation of a generic method, that converts a List<T> or List<List<T>>, to T[] or T[][] respectively. Well, let's just consider a maximum dimension of 2 for now.
List<T> to T[] is quite straight-forward:
public static <T> T[] listToArray(List<T> list, Class<T> clazz) { /**** Null Checks removed for brevity ****/ T[] arr = (T[]) Array.newInstance(clazz, list.size()); for (int i = 0; i < list.size(); ++i) { arr[i] = list.get(i); } return arr; } Now I can call this method as:
List<String> list = new ArrayList<>(Arrays.asList("rohit", "jain")); String[] arr = listToArray(list, String.class); List<List<T>> to T[][] is what gives problems:
Now, here's the problem. Consider the code:
public static <T> T[][] multiListToArray(List<List<T>> listOfList, Class<T> clazz) { // Here I don't know what size to give for 2<sup>nd</sup> dimension // T[][] arr = (T[][]) Array.newInstance(clazz, listOfList.size(), ?); // So, I tried this. But this of course is not type safe // T[][] arr = (T[][]) new Object[listOfList.size()][]; /* Only alternative I had was to iterate over the listOfList to get the maximum out of all the column sizes, which I can give as 2<sup>nd</sup> dimension later on. */ int maxCol = 0; for (List<T> row: listOfList) { if (row.size() > maxCol) { maxCol = row.size(); } } // Now I can pass `maxCol` as 2<sup>nd</sup> dimension T[][] arr = (T[][]) Array.newInstance(clazz, listOfList.size(), maxCol); for (int i = 0; i < listOfList.size(); ++i) { List<T> row = listOfList.get(i); arr[i] = listOfList.get(i).toArray((T[])Array.newInstance(clazz, row.size())); } return arr; } Now, this is what I want to avoid - double iteration of List<List<T>> to be able to create the array. Is there any possibility?