ReedTa
ReedTa

Reputation: 11

Creating a Two Dimensional ArrayList in Java

I've been working on a school project that requires (or at least strongly suggests) using two dimensional ArrayLists in Java (specifically an ArrayList that holds ArrayList of ints). I don't find the syntax too hard to grasp, but the below code has really stumped me:

List<ArrayList<Integer>> arrList2D = new ArrayList<>();
List<Integer> arrList1D = new ArrayList<>();
arrList1D.add(1);
arrList2D.add(arrList1D);

That snippet gives me the error:

Cannot convert List<Integer> to ArrayList<Integer> 

on the very last line. What I find confusing is that I explicitly instantiate arrList1D as an ArrayList. Is there something obvious I'm missing? Would definitely appreciate any help with this. Sorry for any redundant questions.

Upvotes: 1

Views: 971

Answers (2)

billy.mccarthy
billy.mccarthy

Reputation: 122

So the error you are seeing is because arrList1D is of type List meaning it can be any List implementation (though in your case you have chosen ArrayList).

Where as your arrList2D is Declared as List<ArrayList<Integer>> The inner list in this case has to explicitly be of type ArrayList.

There are two ways to make this compile either change the type of arrList1D to be an ArrayList

    List<ArrayList<Integer>> arrList2D = new ArrayList<>();
    ArrayList<Integer> arrList1D = new ArrayList<>();
    arrList1D.add(1);
    arrList2D.add(arrList1D);

Or change the inner type of arrList2D to use List.

    List<List<Integer>> arrList2D = new ArrayList<>();
    List<Integer> arrList1D = new ArrayList<>();
    arrList1D.add(1);
    arrList2D.add(arrList1D);

I would recommend using the second option as it gives you the flexibility to change either the inner or outer List implementations freely.

Upvotes: 0

Zachary
Zachary

Reputation: 1703

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

While you are creating a new ArrayList Object of type Integer, you use a List variable to reference the Object. As far as the compiler knows, the Object arrList1D is referencing is a List, not ArrayList. ArrayList extends List, such that every ArrayList is a List, but not every List is an ArrayList. The error comes when you try add a List Object to a List that only accepts ArrayList Objects More on Java Inheritance.

You will need to instead ensure arrList1D is referenced by an ArrayList variable OR the type of the '2D List' is List, not ArrayList.

List<List<Integer>> arrList2D = new ArrayList<>();
List<Integer> arrList1D = new ArrayList<>();
arrList1D.add(1);
arrList2D.add(arrList1D);

or

List<ArrayList<Integer>> arrList2D = new ArrayList<>();
ArrayList<Integer> arrList1D = new ArrayList<>();
arrList1D.add(1);
arrList2D.add(arrList1D);

Upvotes: 2

Related Questions