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?
答案 0 :(得分:6)
Of course! Add it just like any other ArrayList
, except the type would be ArrayList<String>
.
ArrayList<ArrayList<String>> mainCat = new ArrayList<ArrayList<String>>();
ArrayList<String> subCat = new ArrayList<>();
mainCat.add(subCat);
答案 1 :(得分:1)
why not ? But you need to make a slight change in the definition of mainCat:
List<List<String>> mainCat = new ArrayList<List<String>>();
Because items in mainCat collection will not be String but collections.
答案 2 :(得分:1)
I would use a RewriteRule
for this purpose, because it makes it easier to lookup sub categories based on the main category. If you use a Map
, you actually have no way to determine into which main category a given sub category belongs to. Here's an example using a List<List<String>>
(which automatically keeps main categories in alphabetical order):
TreeMap
This prints out
{A=[A1, A2, A3], B=[B1, B2], C=[C1]} [B1, B2]
答案 3 :(得分:0)
Sure you can.
List<List<String>> mainCat = new ArrayList<ArrayList<String>>();
List<String> subCat = new ArrayList<String>();
mainCat.add(subCat);