Skip to content
Related Articles

Related Articles

Improve Article
Java ArrayList of Arrays
  • Difficulty Level : Basic
  • Last Updated : 04 Dec, 2020

ArrayList of arrays can be created just like any other objects using ArrayList constructor. In 2D arrays, it might happen that most of the part in the array is empty. For optimizing the space complexity, Arraylist of arrays can be used.

ArrayList<String[ ] > geeks = new ArrayList<String[ ] >();

Example:

Input :int array1[] = {1, 2, 3},
       int array2[] = {31, 22},
       int array3[] = {51, 12, 23}
Output: ArrayList of Arrays = {{1, 2, 3},{31, 22},{51, 12, 23}}

Approach: 

  • Create ArrayList object of String[] type, say, list.
  • Store arrays of string, say, names[], age[] and address[] into list object.
  • Print ArrayList of Array.

Below is the implementation of the above approach:

Java




// Java ArrayList of Arrays
import java.io.*;
import java.util.*;
  
class GFG {
    public static void main(String[] args)
    {
        // create an ArryaList of String Array type
        ArrayList<String[]> list = new ArrayList<String[]>();
          
        // create a string array called Names
        String names[] = { "Rohan", "Ritik", "Prerit" };
          
        // create a string array called Age
        String age[] = { "23", "20" };
          
        // create a string array called address
        String address[] = { "Lucknow", "Delhi", "Jaipur" };
          
        // add the above arrays to ArrayList Object
        list.add(names);
        list.add(age);
        list.add(address);
          
        // print arrays from ArrayList
        for (String i[] : list) {
            System.out.println(Arrays.toString(i));
        }
    }
}
Output
[Rohan, Ritik, Prerit]
[23, 20]
[Lucknow, Delhi, Jaipur]

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.




My Personal Notes arrow_drop_up
Recommended Articles
Page :