Saturday, November 16, 2024
Google search engine
HomeLanguagesJavaJava ArrayList of Arrays

Java ArrayList of Arrays

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 ArrayList 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]
RELATED ARTICLES

Most Popular

Recent Comments