ArrayList of arrays Java

Sometimes it may be necessary to store arrays in ArayList in coding. It is also necessary to retrieve the elements of the arrays when required. Another similar concept program is available "Array of Array Lists" that stores array lists in an array of array list.

Example on ArrayList of arrays
import java.util.*;
public class Demo
{
  public static void main(String args[])
  {
    ArrayList al1 = new ArrayList();

    String names[] = { "S N Rao", "Jyostna" };
    Integer marks[] = { new Integer(70), new Integer(80) };
    Double heights[] = { new Double(5.8), new Double(6.1) };

    al1.add(names);
    al1.add(marks);
    al1.add(heights);

    for(Object str[] : al1)
    {
      System.out.println(Arrays.toString(str));
    }
  }
}


ArrayList of arrays
Output screen of ArrayList of arrays

     ArrayList al1 = new ArrayList();

A generics ArrayList al1 is created that stores arrays. Object array is chosen as it permits to add any type of array.

     al1.add(names);
     al1.add(marks);
     al1.add(heights);

The al1 is added with arrays of String, Integer and Double.

     for(Object str[] : al1)
     {
       System.out.println(Arrays.toString(str));
     }

With enhanced for loop, the elements of all the arrays (names, marks and heights) are printed. toStriing() method of Arrays is used to print the elements of each array. toString() method avoids looping.

Alternatively, a generics ArrayList to store string arrays can be taken and added with only string arrays as follows.

     ArrayList al1 = new ArrayList();
     String names[] = { "S N Rao", "Jyostna" };
     String places[] = { "Guntur", "Hyderabad" };
     al1.add(names);
     al1.add(places);

Read also Array of Array Lists.

Leave a Comment

Your email address will not be published.