首先,你的做法是半正确的。
对于二维数组,您可以有ArrayList
的ArrayList
s。
但是......
你初始化你的List
原始类型。从Java 7,你可以改变你分配一个钻石型的推断:
List<List<String>> pods = new ArrayList<>();
在早期版本:
List<List<String>> pods = new ArrayList<List<String>>();
您还需要填充您的列表。
为此,您需要一些迭代。
这是一个完整的Java 7示例(使用List
作为“代码到接口”指南建议)。
String[][] info = {{"pod1", ""}, {"pod2", ""}, {"pod3", ""}, {"pod4", ""}};
List<List<String>> pods = new ArrayList<>();
for (String[] level1: info) {
List<String> list = Arrays.asList(level1);
// use this instead if you intend to modify the inner lists
// List<String> list = new ArrayList<>(Arrays.asList(level1));
pods.add(list);
}
System.out.println(pods);
输出
[[pod1, ], [pod2, ], [pod3, ], [pod4, ]]
现在,一些Java 8魔力:
String[][] info = {{"pod1", ""}, {"pod2", ""}, {"pod3", ""}, {"pod4", ""}};
List<List<String>> pods =
Arrays.stream(info)
.map((a) -> Arrays.asList(a))
// use this instead if you intend to modify the inner lists
// .map((a) -> Arrays.stream(a).collect(Collectors.toList()))
.collect(Collectors.toList());
System.out.println(pods);
(相同)输出
[[pod1, ], [pod2, ], [pod3, ], [pod4, ]]
'Arrays.asList'返回固定大小'List'。我相信你不能使用这个解决方案将元素附加到内部'List'。 –
@ManosNikolaidis这是真的,虽然不是对原始问题的要求。最简单的解决方案是将我的猜测包装在构造函数中。 – Mena