Open In App
Related Articles

Array of ArrayList in Java

Improve Article
Save Article
Like Article

We often come across 2D arrays where most of the part in the array is empty. Since space is a huge problem, we try different things to reduce the space. One such solution is to use jagged array when we know the length of each row in the array, but the problem arises when we do not specifically know the length of each of the rows. Here we use ArrayList since the length is unknown.
Following is a Java program to demonstrate the above concept.

// Java code to demonstrate the concept of 
// array of ArrayList
import java.util.*;
public class Arraylist {
    public static void main(String[] args)
        int n = 5;
        // Here al is an array of arraylist having
        // n number of rows.The number of columns on
        // each row depends on the user.
        // al[i].size() will give the size of the
        // i'th row
        ArrayList<Integer>[] al = new ArrayList[n];
        // initializing
        for (int i = 0; i < n; i++) {
            al[i] = new ArrayList<Integer>();
        // We can add any number of columns to each
        // rows as per our wish
        for (int i = 0; i < n; i++) {
            for (int j = 0; j < al[i].size(); j++) {
                System.out.print(al[i].get(j) + " ");

Output :

1 2 
10 20 30 
34 67 89 12 

The above code works fine, but shows below warning. warning: [unchecked] unchecked conversion
        ArrayList[] al = new ArrayList[n];
  required: ArrayList[]
  found:    ArrayList[]
1 warning

The warning comes basically due to below line.

ArrayList<Integer>[] al = new ArrayList[n];

How to fix above warning?
We cannot use array of ArrayList without warning. We basically need to use ArrayList of ArrayList.

Whether you're preparing for your first job interview or aiming to upskill in this ever-evolving tech landscape, GeeksforGeeks Courses are your key to success. We provide top-quality content at affordable prices, all geared towards accelerating your growth in a time-bound manner. Join the millions we've already empowered, and we're here to do the same for you. Don't miss out - check it out now!

Last Updated : 11 Dec, 2018
Like Article
Save Article
Similar Reads
Complete Tutorials