Reputation: 85
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
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
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