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?
4 Answers 4
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);
Comments
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]
Comments
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.
3 Comments
List as a type argument, the second one uses String. Both have type arguments specifiedSure you can.
List<List<String>> mainCat = new ArrayList<ArrayList<String>>();
List<String> subCat = new ArrayList<String>();
mainCat.add(subCat);
Map<String, List<String>>(mapping main categories into lists of sub categories) would be a better choice then.