0

I have my Integer data in Array Lists of Arrays Lists and I want to convert that data to Lists of List format. How can I do it?

public List<List<Integer>> subsetsWithDup(int[] nums) {

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

    String arrStr = nums.toString();
    ArrayList<Integer> tempList = null;

    for(int i = 0 ; i < arrStr.length()-1 ; i++){
        for(int j = i+1 ; j<arrStr.length() ; j++){

            tempList = new ArrayList<Integer>();

            tempList.add(Integer.parseInt(arrStr.substring(i,j)));

        }

        if(!ansList.contains(tempList)){
            ansList.add(tempList);
        }

    }
    return ansList;
}
5
  • List is the base class of ArrayList,so you can either write List<ArrayList<Integer>> cc = new ArrayList<ArrayList<Integer>>() where your generic type ArrayList<Integer> has to be same. Commented Mar 18, 2019 at 5:44
  • How about this List<List<Integer>> listList = new ArrayList<>(arrayLists); Commented Mar 18, 2019 at 5:55
  • Can you show some code? An ArrayList is already a List. Commented Mar 18, 2019 at 6:00
  • @Thilo an ArrayList<ArrayList<Integer>> is not a List<List<Integer>> Commented Mar 18, 2019 at 6:19
  • @Ferrybig. That is correct. Commented Mar 18, 2019 at 6:26

1 Answer 1

2

It would be best to share the code where you have this issue. However, you should declare the variables as List<List<Integer>>, and then instantiate using an ArrayList.

For example:

public static void main (String[] args) throws java.lang.Exception
{

   List<List<Integer>> myValues = getValues();
   System.out.println(myValues);

}

public static List<List<Integer>> getValues() {
   List<List<Integer>> lst = new ArrayList<>();
   List<Integer> vals = new ArrayList<>();

   vals.add(1);
   vals.add(2);
   lst.add(vals);

   vals = new ArrayList<>();
   vals.add(5);
   vals.add(6);
   lst.add(vals);       

   return lst;
}

In general, program to an interface (such as List).

Based upon the edit to the OP's question, one can see that, as originally suggested, one can change:

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

to

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

And

 ArrayList<Integer> tempList = null;

to

List<Integer> tempList = null;

And the code will then conform to the method's return signature of List<List<Integer>>.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.