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.

5
  • 1
    Why do you need ArrayList<ArrayList<T>> at the first place? Commented Oct 21, 2020 at 11:38
  • @NikolasCharalambidis because ArrayList implements Serializable which List does not. Commented Oct 21, 2020 at 11:40
  • You might find this relevant. stackoverflow.com/questions/1387954/… Commented Oct 21, 2020 at 12:02
  • All standard implementations of java.util.List already implement java.io.Serializable. It's safe to cast if you are sure it's one of them. Commented Oct 21, 2020 at 12:03
  • Serializable is just a constraint of the interface I use. I don't really need it for this specific use-case. But thanks for the info. Commented Oct 21, 2020 at 12:49

1 Answer 1

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

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.