如何在 Java 中创建多维 ArrayList? [英] How to create a Multidimensional ArrayList in Java?
问题描述
无论如何,我对 ArrayLists 还是相当陌生,但我需要它们用于这个项目我正在这样做,如果你们能帮助我,我将不胜感激!
基本上,我需要创建一个多维 ArrayList 来保存字符串值.我知道如何使用标准数组执行此操作,例如 public static String[][] array = {{}}
但这不好,因为我不知道数组的大小,我只知道它会有多少次元.
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/+ 维度的动态可调整大小的数组",请告诉我.
So, if you guys know how to make a 'dynamically resizable array with 2/+ demensions', please could you tell me.
提前致谢,
安迪
Thanks In advance,
Andy
编辑/更新
也许使用变量调整大小或定义标准数组会更容易?但我不知道?
不过,使用我最初的 ArrayList 想法可能更容易……我只需要一个完整的示例代码来创建一个 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
根据您的要求,您可以使用如下所示的 Generic 类来简化访问:
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);
}
}
这篇关于如何在 Java 中创建多维 ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!