Friday, November 21, 2025
HomeLanguagesJavaArrayList of ArrayList in Java

ArrayList of ArrayList in Java

We have discussed that an array of ArrayList is not possible without warning. A better idea is to use ArrayList of ArrayList.




// Java code to demonstrate the concept of
// array of ArrayList
  
import java.util.*;
public class Arraylist {
    public static void main(String[] args)
    {
        int n = 3;
  
        // Here aList is an ArrayList of ArrayLists
        ArrayList<ArrayList<Integer> > aList = 
                  new ArrayList<ArrayList<Integer> >(n);
  
        // Create n lists one by one and append to the 
        // master list (ArrayList of ArrayList)
        ArrayList<Integer> a1 = new ArrayList<Integer>();
        a1.add(1);
        a1.add(2);
        aList.add(a1);
  
        ArrayList<Integer> a2 = new ArrayList<Integer>();
        a2.add(5);
        aList.add(a2);
  
        ArrayList<Integer> a3 = new ArrayList<Integer>();
        a3.add(10);
        a3.add(20);
        a3.add(30);
        aList.add(a3);
  
        for (int i = 0; i < aList.size(); i++) {
            for (int j = 0; j < aList.get(i).size(); j++) {
                System.out.print(aList.get(i).get(j) + " ");
            }
            System.out.println();
        }
    }
}


Output:

1 2 
5 
10 20 30
RELATED ARTICLES

1 COMMENT

Most Popular

Dominic
32405 POSTS0 COMMENTS
Milvus
97 POSTS0 COMMENTS
Nango Kala
6781 POSTS0 COMMENTS
Nicole Veronica
11928 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11995 POSTS0 COMMENTS
Shaida Kate Naidoo
6907 POSTS0 COMMENTS
Ted Musemwa
7164 POSTS0 COMMENTS
Thapelo Manthata
6862 POSTS0 COMMENTS
Umr Jansen
6847 POSTS0 COMMENTS