Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

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.

question from:https://stackoverflow.com/questions/4401850/how-to-create-a-multidimensional-arraylist-in-java

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...