0

I know there is a similar question.
But the question I have here is different.

My problem I have is about on how to create a Multi-dimensional ArrayList. I know like for 2 dimensions I can do this

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

And I can keep on adding the dimensions like that. But for an array like that can be managable until 3 or 4 dimensions. (Readability will decrease if keep on doing that)

Is there any way or any class such that I can declare the dimensions of the ArrayList dynamically. I mean that the dimensions of the array should be declared at run time.
The above mentioned 2+ dimensional array is hard coded.

How can I achieve dynamic dimension declaration?

Ruthvik
  • 790
  • 5
  • 28
  • Why don't you start by writing the interface that you'd like your multidimensional array list to have -- the methods which get and set elements, and get the number of dimensions and the sizes of the array at particular points. – tgdavies May 20 '22 at 11:42
  • How would you expect to reference it? – matt May 20 '22 at 11:43
  • @matt, I expect it to be like a list as it is in python. something very much similar like that – Ruthvik May 20 '22 at 11:48
  • You could write a class that uses, .get(int... loc), and grab from your set of arraylists. I agree with tgdavies, you should make an interface you want. It might still be backed by ArrayList but you wouldn't have to write it out. – matt May 20 '22 at 11:58
  • 1
    [What is the XY problem?](https://meta.stackexchange.com/questions/66377/what-is-the-xy-problem/66378#66378) – Holger May 20 '22 at 12:11

2 Answers2

2

You could try something like this:

int dims = 3;
ArrayList<Object> root = new ArrayList<>();
ArrayList<Object> current = root;
ArrayList<Object> previous = null;
for(int i = 0; i < dims; i++){
    previous = current;
    current=new ArrayList<Object>();
    previous.add(current);
}
Profingo
  • 21
  • 1
1

I would create a wrapper like a LinkedList with its next dimension as a member as well as the data:

public final class Dimension {

    private final List<Integer> data = new ArrayList<>();
    private final Dimension nextDimension;

    public Dimension(Dimension next) {
        this.nextDimension = next;
    }

    public static Dimension init(int depth) {
        Dimension d = null;
        for (int i = 0; i < depth; i++) {
            d = new Dimension(d);
        }
        return d;
    }
}

It is also possible to make nextDimension mutable if needed.

Stefan Warminski
  • 1,845
  • 1
  • 9
  • 18