Home > Software engineering >  Return a List<List<E>> in Java
Return a List<List<E>> in Java

Time:02-19

i have to write a method that return the same type as in title. But as you all know, List is an interface, and therefore has no instance. In my code, i use 'ArrayList<ArrayList>listList' to store the information to return. But as i try to return listList, such Error occurs

    Type mismatch: cannot convert from List<ArrayList<E>> to List<List<E>>

So how can i return it? I've tried to declare

            List<ArrayList<E>>listList// still cant return
    List<List<E>>listList//this cant be declared

Thanks a lot!

CodePudding user response:

The returned value may look just like this:

public static <E> List<List<E>> foo() {
    return new ArrayList<>();
}
// or immutable empty list
public static <E> List<List<E>> foo() {
    return Collections.emptyList();
}

I use 'ArrayListlistList' to store the information to return The result to return can and should be declared as List<List<E>> but it has to be initialized properly with the list implementation:

public static <E> List<List<E>> bar(E item) {
    List<List<E>> result = new ArrayList<>();
    result.add(new ArrayList<>());
    result.get(0).add(item);
    return result;
}

public static <E> List<List<E>> bar1(E item) {
    List<List<E>> result = new ArrayList<>();
    result.add(Arrays.asList(item));
    return result;
}

Starting from Java 9, List.of may be used (an immutable List implementation is returned):

public static <E> List<List<E>> bar2(E item) {
    return List.of(
        List.of(item)
    );
}

CodePudding user response:

This should help.

//Simply decalare your result type to be List<List<E>> and initialize it with new ArrayList();
List<List<E>> res = new ArrayList();
return res;
  • Related