Java ArrayList of arrays example shows how to create and use ArrayList of arrays in Java. The example also shows how to iterate through ArrayList of arrays in Java.
How to create ArrayList of arrays in Java?
You can create an ArrayList of arrays just like with any other objects using ArrayList constructor. If you want to create ArrayList of String arrays, you can use below given syntax.
1 |
ArrayList<String[]> aList = new ArrayList<String[]>(); |
This will create an ArrayList of String arrays.
Note: While declaring the ArrayList of arrays, we cannot specify the length of the String array objects it is going to have. Doing so will result in a compilation error. This also means that you can add arrays of different sizes to the same ArrayList.
Example of ArrayList of arrays
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
package com.javacodeexamples.collections.arraylist; import java.util.ArrayList; public class ArrayListOfArraysExample { public static void main(String[] args) { //Create ArrayList of arrays ArrayList<String[]> aListArrays = new ArrayList<String[]>(); /* * To add arrays to ArrayList, use * public boolean add(E e) method. */ aListArrays.add(new String[]{"element1"}); aListArrays.add(new String[]{"element1", "element2"}); aListArrays.add(new String[]{"element1", "element2", "element3"}); //this will add empty array to ArrayList aListArrays.add(new String[]{}); System.out.println("ArrayList contains " + aListArrays.size() + " arrays" ); /* * While creating ArrayList of String arrays, we cannot * specify the size of arrays. That means we can have arrays * of different size in the ArrayList. * * While getting the arrays back from the ArrayList, check * the array size before accessing the array elements using * length property. */ //iterate through ArrayList of arrays for(String[] strArray : aListArrays){ System.out.print("Array size is: " + strArray.length); System.out.print(" ["); //iterate through array using its length for(int i = 0 ; i < strArray.length; i++){ System.out.print( strArray[i] + " "); } System.out.println("]"); } } } |
Output
1 2 3 4 5 |
ArrayList contains 4 arrays Array size is: 1 [element1 ] Array size is: 2 [element1 element2 ] Array size is: 3 [element1 element2 element3 ] Array size is: 0 [] |
Please note that ArrayList accepts null values. Always make sure that the object retrieved from ArrayList is not null before accessing its method or properties. Not doing so may result in NullPointerException, if the object is null.
This example is a part of the Java ArrayList tutorial and Java Array tutorial.
Please let me know your views in the comments section below.