How to create a Multidimensional ArrayList in Java?

How to create a Multidimensional ArrayList in Java?

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

If youre 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 whats going on. Also, youll need to import java.util.ArrayList; for this, if youre making use of the Java class.

How to create a Multidimensional ArrayList in Java?

ArrayList<ArrayList<String>>

http://download.oracle.com/javase/6/docs/api/java/util/ArrayList.html

http://en.wikipedia.org/wiki/Generics_in_Java

Leave a Reply

Your email address will not be published.