0

精简版

如何一次性将值添加到 3 维数组列表?

List<List<List<String>>> FD = new ArrayList<List<List<String>>>();

我了解到,对于普通的 Arraylist,可以执行以下操作

List<String> R = new ArrayList<String>();
R.addAll(Arrays.asList("A","B","C","D","E"));

更长的版本

注意:我将使用“->”符号来表示“确定”。
将 A -> B 解读为“A 决定 B”。

我正在尝试以某种方式捕获以下信息。
A -> B, A,B -> C, B -> D,E

我觉得 3D 列表会派上用场,因为我用下面的形式描绘了它

F[             --> Outermost List starts
  [            --> Middle List start (first of the three middle lists)
   [A],
   [B]
  ],            --> Middle List end
  [
   [A,B],        --> Innermost list start and end (first of the two inner lists in this middle list)
   [C]
  ],
  [
   [B],
   [D,E]
  ]
 ]             --> Outermost List ends

我选择了一个列表,因为它的大小在某种程度上是动态的(除了每个中间列表总是只有 2 个内部列表)

如果您能向我展示一种填充此类列表的简单方法,我将不胜感激。

如果您有一些替代实施建议,我也愿意接受。

提前致谢

4

2 回答 2

0

像这样。Lists.newArrayList我从番石榴图书馆复制。

import java.util.ArrayList;
import java.util.Collections;

public class Test {
    public static <E> ArrayList<E> newArrayList(E... elements) {
        ArrayList<E> list = new ArrayList<>(elements.length);
        Collections.addAll(list, elements);
        return list;
    }

    public static void main(String[] args) {

        ArrayList<ArrayList<ArrayList<String>>> lists = newArrayList(
            newArrayList(
                newArrayList("A"),
                newArrayList("B")
            ),
            newArrayList(
                newArrayList("A", "B"),
                newArrayList("C")
            ),
            newArrayList(
                newArrayList("B", "D"),
                newArrayList("E")
            )
        );

        System.out.println(lists);
    }
}
于 2013-10-25T19:05:37.827 回答
0

这并不是严格回答您的问题(答案不涉及列表),而是另一种方法。在您的问题中,您有一些坐标来表示每个String值。也许使用 aMap会是最好的。

类来定义键:

public class Coordinate {
    private int x, y, z;

    // Static factory to make your code read a little better
    public static Coordinate create(int x, int y, int z) {
        return new Coordinate(x, y, z);
    }

    public Coordinate(int x, int y, int z) {
        // set this.x, this.y, this.z
    }

    public boolean equals(Object o) {
        // Compare this.x, y, z with o.x, y, z
    }

    public int hashCode() {
        // I'm sure you can come up with something
    }
}

现在,您可以执行以下操作:

Map<Coordinate, String> map = new HashMap<Coordinate, String>();
map.put(Coordinate.create(1, 2, 3), "Some value");

// Prints out "Some value"
System.out.println(map.get(Coordinate.create(1, 2, 3));
于 2013-10-25T19:24:12.820 回答