Java:数组的数组列表

我想创建一个包含 2 个元素的数组的数组列表。所以,我有未知的行和已知的列(即2)。例如 [{name1, ID1}, {name2, ID2}, ...]

我还必须返回这个数组列表。

我尝试使用

ArrayList<arr> alist = new ArrayList<arr>();

但不知道如何继续。

请指教。


慕勒3428872
浏览 132回答 2
2回答

隔江千里

当你定义一个ArrayList时必须使用一个类。在这种情况下,您可以使用 Person 类:class Person {&nbsp; &nbsp; private Integer id;&nbsp; &nbsp; private String name;&nbsp; &nbsp; public Integer getId() {&nbsp; &nbsp; &nbsp; &nbsp; return id;&nbsp; &nbsp; }&nbsp; &nbsp; public void setId(Integer id) {&nbsp; &nbsp; &nbsp; &nbsp; this.id = id;&nbsp; &nbsp; }&nbsp; &nbsp; public String getName() {&nbsp; &nbsp; &nbsp; &nbsp; return name;&nbsp; &nbsp; }&nbsp; &nbsp; public void setName(String name) {&nbsp; &nbsp; &nbsp; &nbsp; this.name = name;&nbsp; &nbsp; }}然后,我们可以定义一个 Person 的 ArrayList:ArrayList<Person> array = new ArrayList<Person>();array.get(0).getId();array.get(0).getName();

GCT1015

我在这里提出了两种简单的方法。但是,您还可以想到更多这样的方法。import java.util.ArrayList;import java.util.HashMap;import java.util.List;import java.util.Map;public class Main {&nbsp; &nbsp; public static void main(String[] a) {&nbsp; &nbsp; &nbsp; &nbsp; List<String[]> list = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; String[] arr;&nbsp; &nbsp; &nbsp; &nbsp; arr = new String[2];&nbsp; &nbsp; &nbsp; &nbsp; arr[0] = "name1";&nbsp; &nbsp; &nbsp; &nbsp; arr[1] = "ID1";&nbsp; &nbsp; &nbsp; &nbsp; list.add(arr);&nbsp; &nbsp; &nbsp; &nbsp; arr = new String[2];&nbsp; &nbsp; &nbsp; &nbsp; arr[0] = "name2";&nbsp; &nbsp; &nbsp; &nbsp; arr[1] = "ID2";&nbsp; &nbsp; &nbsp; &nbsp; list.add(arr);&nbsp; &nbsp; &nbsp; &nbsp; // Test&nbsp; &nbsp; &nbsp; &nbsp; for (String[] arrElem : list) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(arrElem[0] + "\t" + arrElem[1]);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; // Another option is to create a list of maps&nbsp; &nbsp; &nbsp; &nbsp; List<Map<String, String>> list2 = new ArrayList<>();&nbsp; &nbsp; &nbsp; &nbsp; Map<String, String> map = null;&nbsp; &nbsp; &nbsp; &nbsp; map = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; map.put("name1", "ID1");&nbsp; &nbsp; &nbsp; &nbsp; list2.add(map);&nbsp; &nbsp; &nbsp; &nbsp; map = new HashMap<>();&nbsp; &nbsp; &nbsp; &nbsp; map.put("name2", "ID2");&nbsp; &nbsp; &nbsp; &nbsp; list2.add(map);&nbsp; &nbsp; &nbsp; &nbsp; // Test&nbsp; &nbsp; &nbsp; &nbsp; for (Map<String, String> mapElem : list2) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; System.out.println(mapElem);&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }}输出:name1&nbsp; &nbsp;ID1name2&nbsp; &nbsp;ID2{name1=ID1}{name2=ID2}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java