How to create a Multidimensional ArrayList in Java?

arraylist, java, multidimensional-array

Solution

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

Problem

I need to create a multidemensional ArrayList to hold String values. I know how to do this with a standard array, like so: `public static String[][] array = {{}}` but this is no good because I don't know the size of my array, all I know is how many dimensions it will have. How can I make a 'dynamically resizable array with 2/+ demensions'? Edit/Update Maybe it would be easier to resize or define a standard array using a varible? But I don't know? It's probably easier to use my original idea of an ArrayList though... All I need is a complete example code to create a 2D ArrayList and add so example values to both dimensions without knowing the index.

Original source

Related problems