Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I make an ArrayList in an ArrayList (java)?

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?

like image 894
Max Echendu Avatar asked Feb 09 '23 10:02

Max Echendu


2 Answers

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);
like image 69
deezy Avatar answered Feb 19 '23 18:02

deezy


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]
like image 45
Mick Mnemonic Avatar answered Feb 19 '23 20:02

Mick Mnemonic