问题描述
我想用户输入存储到一个ArrayList那么ArrayList中放入另外一个ArrayList中。所以,有点像一个主要类别,其中包含包含数据的子类别。
下面是一些code的:
的ArrayList<串GT; mainCat =新的ArrayList<>();
ArrayList的<串GT; SUBCAT =新的ArrayList<>();
我能添加SUBCAT的ArrayList中的mainCat的ArrayList
我会用地图
用于此目的,因为它可以更容易地查找子类别的基础上主要类别。如果使用列表<名单<弦乐>>
,你实际上有没有办法来确定给定的子类别属于到其中的主要类别。下面是一个使用 TreeMap的
(自动保持主要类别按字母顺序)的例子:
地图<字符串列表<串GT;> mainCategories =新TreeMap的<>();
mainCategories.put(A,Arrays.asList(A1,A2,A3));
mainCategories.put(B,Arrays.asList(B1,B2));
mainCategories.put(C,Arrays.asList(C));的System.out.println(mainCategories);
的System.out.println(mainCategories.get(B));
这打印出
{A = [A1,A2,A3],B = [B1,B2],C = [C 1]}
[B1,B2]
I' would like to store user input into an ArrayList then place that ArrayList into another ArrayList. So sort of like a main category, which contains sub-categories that contain data.
Here is some of the code:
ArrayList<String> mainCat = new ArrayList<>();
ArrayList<String> subCat = new ArrayList<>();
Could I add the "subCat" ArrayList in the "mainCat" ArrayList?
I would use a Map
for this purpose, because it makes it easier to lookup sub categories based on the main category. If you use a List<List<String>>
, you actually have no way to determine into which main category a given sub category belongs to. Here's an example using a TreeMap
(which automatically keeps main categories in alphabetical order):
Map<String, List<String>> mainCategories = new TreeMap<>();
mainCategories.put("A", Arrays.asList("A1", "A2", "A3"));
mainCategories.put("B", Arrays.asList("B1", "B2"));
mainCategories.put("C", Arrays.asList("C1"));
System.out.println(mainCategories);
System.out.println(mainCategories.get("B"));
This prints out
{A=[A1, A2, A3], B=[B1, B2], C=[C1]} [B1, B2]
这篇关于我可以在一个ArrayList(Java)的一个ArrayList?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!