-1

Im trying to create a Three Dimensional List that looks like this:

Main List
  -List1
     -Sublist1
     -Sublist2
     -Sublist3
  -List2
     -Sublist1
     -Sublist2
  -List3
     -Sublist1
     -Sublist2
     -Sublist3
     -Sublist4

With this, let's say I want to access the element "List2, Sublist1", I want to get the access like using list.get(0).get(1).get(0)

I know that I can create a list of lists, using the following code

List<List<Integer>> lists = new ArrayList<List<Integer>>();
for (int i = 0; i < 4; i++) {
    List<Integer> list = new ArrayList<>();
    lists.add(list);
}

Is there a way to create a Three Dimensional List? Or in which way should I try to do this?

Kito
  • 3
  • 3

1 Answers1

0

You can create the 3D list with the following line

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

But to add values in the list (write to the list), you've to work from inside to outside. Create the lists that are to be nested and populate them first. Then add them to the outer list.

    List<Integer> sublist = new ArrayList<Integer>();
    //Populate sublist
    sublist.add(0);
    sublist.add(1);
    sublist.add(2);
    
    List<List<Integer>> list = new ArrayList<List<Integer>>();
    list.add(sublist);
    
    mainlist.add(list);

But a better approach would be to do it with classes and objects. If you're looking for that, let me know in the comments, I can add that.

ram
  • 437
  • 2
  • 12
  • This works pretty well, I found how to adapt it to my code and is actually working as I want. Thanks you :) – Kito May 18 '21 at 19:24