javalistarraylistincompatibletypeerror

error: incompatible types: List<Integer> cannot be converted to ArrayList<Integer>


I have found a few questions similar to the problem I am facing, but I couldn't find solution. Example: Incompatible types List of List and ArrayList of ArrayList, Not able to understand how to define a List of List in java

The program should return list of lists. So, I declared a list of lists and then trying to add arraylists to it.

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

But, when I am trying to access each arraylist item from the list of lists as below, I get the error: incompatible types: List<Integer> cannot be converted to ArrayList<Integer>

for(ArrayList<Integer> subset:allsubsets)

When I try to convert the line to for(List<Integer> subset:allsubsets), it throws error that add, addAll don't exist for List type, which makes sense. Please help me understand how to access elements of list of lists in this case.

public List<List<Integer>> subsets(int[] nums) {
    List<Integer> arrayList = new ArrayList<Integer>();
    for(int i:nums) {
        arrayList.add(i);
    }
    return subsets(arrayList,nums.length);
}

public List<List<Integer>> subsets(List<Integer> arrayList, int index) {
    List<List<Integer>> allsubsets;
    if(index == -1) {
         allsubsets = new ArrayList<List<Integer>>();
         allsubsets.add(new ArrayList<Integer>());
    }
    else {
        allsubsets = subsets(arrayList, index-1);
        int item = arrayList.get(index);
        List<List<Integer>> moresubsets =  new ArrayList<List<Integer>>();
        for(ArrayList<Integer> subset:allsubsets) { 
        //The line above throws error as I created list of lists

            List<Integer> newsubset = new ArrayList<Integer>(); //create new subset
            newsubset.addAll(subset); // add all old items
            newsubset.add(item); // add new item
            moresubsets.add(newsubset); //add subset to moresubsets
        }
        allsubsets.add(moresubsets); // add to actual one
    }
  return allsubsets;
}

Note: If I change the return type to arraylist of arraylists, it works for me. But, I want to make it work for the list of lists


Solution

  • Correct way to iterate your list of list should be:

        for(List<Integer> subset:allsubsets) { 
    

    instead of:

        for(ArrayList<Integer> subset:allsubsets) { 
    

    List<List<Integer>> allsubsets is declared as List of List, but the implementation is unknown.

    Only you know the type of nested List is ArrayList, so either change foreach to use List<Integer> or manually cast your List<Integer> to ArrayList<> (this is not preferred)

    One more thing:

        allsubsets.add(moresubsets); // add to actual one
    

    This try to add a List of List (List<List<Integer>>) as element which should be List<Integer> hence compile error.

    Change that statement to:

      allsubsets.addAll(moresubsets);