0

After trying for 2 Days, finally asking on stackoverflow: How to pass a 2D Arraylist to 2 D List

Below is the code:

public class Main {

    static void fn1(List<List<Integer>> x){
        System.out.println(x);
    }
    public static void main(String[] args) {

        // Here aList is an ArrayList of ArrayLists
        ArrayList<ArrayList<Integer>> aList =
                new ArrayList<ArrayList<Integer>>();

        // Create n lists one by one and append to the
        // master list (ArrayList of ArrayList)
        ArrayList<Integer> a1 = new ArrayList<Integer>();
        a1.add(1);
        a1.add(2);
        aList.add(a1);

        ArrayList<Integer> a2 = new ArrayList<Integer>();
        a2.add(5);
        aList.add(a2);

        ArrayList<Integer> a3 = new ArrayList<Integer>();
        a3.add(10);
        a3.add(20);
        a3.add(30);
        aList.add(a3);

        for (int i = 0; i < aList.size(); i++) {
            for (int j = 0; j < aList.get(i).size(); j++) {
                System.out.print(aList.get(i).get(j) + " ");
            }
            System.out.println();
        }

        fn1(aList);
    }
}

I am receiving the error:

Error:(41, 13) java: incompatible types: java.util.ArrayList<java.util.ArrayList<java.lang.Integer>> cannot be converted to java.util.List<java.util.List<java.lang.Integer>>

I have a constrain that I can't change the signature of fn1.

Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
Devender Goyal
  • 1,450
  • 3
  • 18
  • 26

1 Answers1

4

Initialise the Object using the List interface instead of the concrete class.

public static void main(String[] args) {
        // Here aList is an ArrayList of ArrayLists
        List<List<Integer>> aList =
            new ArrayList<List<Integer>>();
Lomtrur
  • 1,703
  • 2
  • 19
  • 35
Pete
  • 205
  • 2
  • 14