-1

I am trying to solve a leetcode problem where I have a function and I am supposed to return a List of a List. eg. public List < List < Integer>> func(TreeNode root)

To solve this problem, I wish to create another function where I pass an empty List of List and eventually return this List of List as my answer.

List < List < Integer >> ret = new List < List < Integer >>();

However this leads to an error, List is abstract; cannot be instantiated.

If I change this to

ArrayList < ArrayList < Integer >> ret = new ArrayList < ArrayList <Integer > >();

I cannot convert the ArrayList < ArrayList < Integer > to List < List < Integer > >.

I can't even get this to work.

List < List < Integer > > ret = new ArrayList < ArrayList < Integer > > ();

Can you suggest some way around this? I have been facing this kind of issue a lot of times and usually find some workaround to solve this. What is the proper method to resolve this?

Dulaj Kulathunga
  • 1,248
  • 2
  • 9
  • 19
Vivek
  • 165
  • 3
  • 9
  • `List < List < Integer > > ret = new ArrayList < List < Integer > > ()` – Eran Oct 10 '19 at 05:12
  • 2
    It might sound rude but stop coding at leetcode and learn your language. Learn what is the difference between class, abstract class and interface. – Ashvin Sharma Oct 10 '19 at 05:15
  • 2
    Possible duplicate of [Working with a List of Lists in Java](https://stackoverflow.com/questions/1474954/working-with-a-list-of-lists-in-java) – Tom Oct 10 '19 at 05:15
  • Even though a `ArrayList` is a `List`, a `ArrayList>` is *not* a `List>`. See https://stackoverflow.com/questions/2745265/is-listdog-a-subclass-of-listanimal-why-are-java-generics-not-implicitly-po. – Andy Turner Oct 10 '19 at 05:22

1 Answers1

2

Only at instantiation do you need the concrete class. This should work

List<List<Integer>> listOfLists = new ArrayList<>();

Which is shorthand for

List<List<Integer>> listOfLists = new ArrayList<List<Integer>>();
Mark Peters
  • 80,126
  • 17
  • 159
  • 190