如何在Java中创建多维的ArrayList? [英] How to create a Multidimensional ArrayList in Java?

查看:1424
本文介绍了如何在Java中创建多维的ArrayList?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是相当新的的ArrayList但无论如何,我需要他们为这个项目,我这样做,如果你们能帮助我,我会感激之余!结果
基本上,我需要创建一个ArrayList的期多维持有字符串值。我知道如何用一个标准数组做到这一点,像这样公共静态的String [] []数组= {{}} 但是,这不是一件好事,因为我不知道我的数组的大小,我只知道它有多少demensions有。

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.

所以,如果你们知道如何做一个动态调整大小的数组,2 / + demensions',请你能告诉我。

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

在此先感谢,结果
刘德华

Thanks In advance,
Andy

编辑/更新

也许会更容易调整或使用varible定义一个标准的阵列?但我不知道吗?结果
它可能更容易使用,虽然我原来的一个ArrayList的想法...所有我需要的是一个完整的例子code创建一个2D ArrayList和不知道添加索引,以便例如值这两个方面。

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.

推荐答案

的ArrayList< ArrayList的<串GT;>阵列=新的ArrayList< ArrayList的<串GT;>();

根据您的要求,您可以使用一个类像下面这样做更容易访问:

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

这篇关于如何在Java中创建多维的ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆