Andy Andy - 7 months ago 5
Java Question

How to create a Multidimensional ArrayList in Java?

I'm fairly new to ArrayLists anyway but I need them for this project I'm doing so if you guys could help me I would be more than grateful!

Basically, 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 demensions it will have.

So, if you guys know how to make a 'dynamically resizable array with 2/+ demensions', please could you tell me.

Thanks In advance,

Andy

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.

Answer

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

Depending on your requirements, you might use a 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);
    }
}
Comments