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

I would like to save user input in an ArrayList and then put that ArrayList in another ArrayList. So it’s kind of like the main category that contains subcategories containing data.

Here are some of the code:

ArrayList<String> mainCat = new ArrayList<>(); ArrayList<String> subCat = new ArrayList<>(); 

Can I add an ArrayList "subCat" to an ArrayList "mainCat"?

+4
source share
4 answers

I would use Map for this purpose, because it makes it easier to find subcategories based on the main category. If you use List<List<String>> , you actually have no way to determine which main category this subcategory belongs to. Here is an example of using TreeMap (which automatically saves the 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")); 

Will print

  {A = [A1, A2, A3], B = [B1, B2], C = [C1]}
 [B1, B2]
+1
source

Sure! Add it just like any other ArrayList , except for the type ArrayList<String> .

 ArrayList<ArrayList<String>> mainCat = new ArrayList<ArrayList<String>>(); ArrayList<String> subCat = new ArrayList<>(); mainCat.add(subCat); 
+6
source

why not? But you need to make a slight change to the definition of mainCat:

 List<List<String>> mainCat = new ArrayList<List<String>>(); 

Since the elements in the mainCat collection will not be a String, but a collection.

+1
source

Of course you can.

 List<List<String>> mainCat = new ArrayList<ArrayList<String>>(); List<String> subCat = new ArrayList<String>(); mainCat.add(subCat); 
0
source

All Articles