Thursday, July 4, 2024
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]
Nokonwaba Nkukhwana
Experience as a skilled Java developer and proven expertise in using tools and technical developments to drive improvements throughout a entire software development life cycle. I have extensive industry and full life cycle experience in a java based environment, along with exceptional analytical, design and problem solving capabilities combined with excellent communication skills and ability to work alongside teams to define and refine new functionality. Currently working in springboot projects(microservices). Considering the fact that change is good, I am always keen to new challenges and growth to sharpen my skills.
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments