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?
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);
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]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With