0

What's the best / most performant way to cast a List<List<T>> to ArrayList<ArrayList<T>>?

Let's assume I have an interface IFoo.getListOfLists() which will give me the List<List<T>>. Let's also assume I know that these List<List<T>> are in fact instances of ArrayList<ArrayList<T>>.

One simple solution would be:

    ArrayList<ArrayList<T>> result = new ArrayList<>();
    for (List<T> arrayList : IFoo.getListOfLists()) {
        result.add((ArrayList<T>)arrayList);
    }

but is there a better approach? Especially, because I already know that the instances are in fact ArrayLists.

Alex
  • 1,857
  • 3
  • 36
  • 51

1 Answers1

1

since the type information for the List is absent at runtime, you can simply cast to ArrayList:

import java.util.ArrayList;
import java.util.List;

public class CastListList {

    public static void main(final String[] args) {
        final List<List<String>> strings = new ArrayList<>();
        strings.add(new ArrayList<>());
        strings.get(0).add("Hello World!");

        final ArrayList<ArrayList<String>> arrayList = cast(strings);
        System.out.println(arrayList.get(0).get(0));
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    private static <T> ArrayList<ArrayList<T>> cast(final List<List<T>> list) {
        return (ArrayList) list;
    }
}
benez
  • 1,856
  • 22
  • 28