Home > Software design >  How to create Multidimensional arraylist in Java dynamically?
How to create Multidimensional arraylist in Java dynamically?

Time:05-20

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?

CodePudding user response:

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);
}

CodePudding user response:

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.

  • Related