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?

5
  • 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. Commented May 20, 2022 at 11:42
  • How would you expect to reference it? Commented May 20, 2022 at 11:43
  • @matt, I expect it to be like a list as it is in python. something very much similar like that Commented May 20, 2022 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<ArrayList< .... > but you wouldn't have to write it out. Commented May 20, 2022 at 11:58
  • 1
    What is the XY problem? Commented May 20, 2022 at 12:11

2 Answers 2

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);
}
Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.