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
import java.io.*;
import java.util.*;
class GFG {
public static void main(String[] args)
{
ArrayList<String[]> list = new ArrayList<String[]>();
String names[] = { "Rohan" , "Ritik" , "Prerit" };
String age[] = { "23" , "20" };
String address[] = { "Lucknow" , "Delhi" , "Jaipur" };
list.add(names);
list.add(age);
list.add(address);
for (String i[] : list) {
System.out.println(Arrays.toString(i));
}
}
}
|
Output
[Rohan, Ritik, Prerit]
[23, 20]
[Lucknow, Delhi, Jaipur]
Last Updated :
08 Oct, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...