How to create a Multidimensional ArrayList in Java?

If you're allowed to use predefined Java classes, you could do something like:

private static ArrayList<ArrayList<String>> biDemArrList = new ArrayList<ArrayList<String>>();

Then you can add new elements, something like:

ArrayList<String> temp = new ArrayList<String>(); // added () 
temp.add("Hello world.");
biDemArrList.add(temp);

Hope you can understand what I mean and what's going on. Also, you'll need to import java.util.ArrayList; for this, if you're making use of the Java class.


ArrayList<ArrayList<String>> array = new ArrayList<ArrayList<String>>();

Depending on your requirements, you might use a Generic class like the one below to make access easier:

import java.util.ArrayList;

class TwoDimentionalArrayList<T> extends ArrayList<ArrayList<T>> {
    public void addToInnerArray(int index, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }
        this.get(index).add(element);
    }

    public void addToInnerArray(int index, int index2, T element) {
        while (index >= this.size()) {
            this.add(new ArrayList<T>());
        }

        ArrayList<T> inner = this.get(index);
        while (index2 >= inner.size()) {
            inner.add(null);
        }

        inner.set(index2, element);
    }
}