2

I have a function that returns a list of lists of integers

public List<List<Integer>> threeSum(int[] nums)

Obviously I can't directly instantiate a List so I chose to use an ArrayList and tried to instantiate my return value as such:

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

The above did not work but this did:

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

My understanding is that List is an interface that ArrayList inherits from. Why, then, can I instantiate an ArrayList of Lists and be ok but I can't instantiate an ArrayList of ArrayLists?

For readability the first few lines of my function look as such:

public List<List<Integer>> threeSum(int[] nums) {
    List<List<Integer>> ans = new ArrayList<List<Integer>>();
    if (nums.length < 3) return ans;
  • 1
    [A closely related question](https://stackoverflow.com/q/2745265) which has the distinct advantage of having been answered by Jon Skeet. – Dawood ibn Kareem Jun 20 '18 at 02:28

3 Answers3

2

This is because an ArrayList<ArrayList<Integer>> is NOT a List<List<Integer>>.

The reason is that a List<List<Integer>> is something that you should be able to add a LinkedList<Integer> to. But you can't add a LinkedList<Integer> to an ArrayList<ArrayList<Integer>> because it's the wrong type.

Therefore, if you've got an ArrayList<ArrayList<Integer>>, you can never treat it as a List<List<Integer>>, or reference it with a variable of type List<List<Integer>>

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
1

This is Java Generics. List<List<Integer>> ans = new ArrayList<ArrayList<Integer>>() does not work because the outer list expects itself to keep List<Integer>, not ArrayList<Integer>.

Consider this:

List<Number> list = new ArrayList<Integer>();

This does not work either, because the list expects Number, not Integer.

Anyway when nesting lists, you need to instantiate inner lists as well. Lists of Lists do not work like multidimensional arrays.

Jai
  • 8,165
  • 2
  • 21
  • 52
1

but I can't instantiate an ArrayList of ArrayLists?

because you specified type of ans as List of Lists not List of ArrayLists.

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

The above did not work

I guess it will work if declaration will be:

List<? extends List<Integer>> ans = new ArrayList<ArrayList<Integer>>();

Vadim
  • 4,027
  • 2
  • 10
  • 26
  • True. Another way is to declare as List> ans = new ArrayList>();. But the one mentioned in the above answer is the best as it is not coupled to any concrete implementaion of list – ptk Jun 20 '18 at 02:31