user2403909
user2403909

Reputation: 85

How to instantiate a List<List<Integer>>?

I encountered a problem while solving problems on LeetCode. The question has a form:

public List<List<Integer>> generate(){

}

that requires returning a List<List<Integer>>. I know for List<T> I can do a LinkedList<T> or ArrayList<T>. How can I instantiate it that the compiler would not complain? Thanks

Upvotes: 0

Views: 3260

Answers (2)

Strikeskids
Strikeskids

Reputation: 4052

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

Then when you want to add stuff to it do

List<Integer> innerList = new ArrayList<Integer>(); myList.add(innerList);

Upvotes: 1

user2357112
user2357112

Reputation: 281958

return new ArrayList<List<Integer>>();

The outer list type needs to be a concrete type like ArrayList or LinkedList, but the inner list type should be List. On more recent Java versions, you can do

return new ArrayList<>();

Upvotes: 2

Related Questions