In this article, we will take a look at creating list of arrays in java with examples and explanation.
A java array is a collection of elements and a list is also a collection of elements.
Difference between the two is that an array is of fixed size while a list is dynamic, meaning it can grow and shrink in size when required.
List of array means that each element of a list is an array. It can be visualized as below.
Each index or position of the list points to an array. Indexes which do not point to any array or are empty are set to null
.
Example program
public class ListOfArrayExample { public static void main(String[] args) { // create a list of arrays List<Integer[]> numbers = new ArrayList<Integer[]>(); // create integer arrays Integer[] arrOne = {1,2,3,4}; Integer[] arrTwo = {5,6,7,8}; // add to list numbers.add(arrOne); numbers.add(arrTwo); // iterate over list for (Integer[] array : numbers) { System.out.println(Arrays.toString(array)); } } }
Explanation
Above example creates a list which shall hold elements of type Integer[]
(array of integers) as
List<Integer[]> numbers = new ArrayList<Integer[]>();
This means that each of its index will point to an integer array. Remember that List
is an interface and ArrayList is its implementation class.
Next, initialize two integer arrays and add them to the list with its add()
method.
Finally, iterate over the list using enhanced for loop. Note the type of loop variable will be the type of elements in the list.
In this case, it is an Integer[]
. Thus, we are iterating of a list of arrays.
In every iteration, the array is printed to the console using Arrays.toString()
method.
Output of this program will be
which shows that each of the list element is an array.
In the previous example, we stored integer arrays in a list. But sometimes we are not sure about the type of array or the list is supposed to contain arrays of different types.
In this case, the type of list elements should be Object[]
. Example,
public class ListOfObjectArrayExample { public static void main(String[] args) { // create a list of object array List<Object[]> list = new ArrayList<Object[]>(); // create string array String[] arrOne = {"list", "of", "array", "example"}; // create integer array Integer[] arrTwo = {5, 6, 7, 8}; // add to list list.add(arrOne); list.add(arrTwo); // iterate over list for (Object[] array : list) { System.out.println(Arrays.toString(array)); } } }
This will print
In this example, we are simply printing the array.
In a real world application, when the list contains values of different data types, you need to check their types with instanceof
operator and perform type casting to properly use them.
Note that starting java 7, you are no longer required to provide the type of list elements at the assignment side(right side).
Thus, you can create a list as
List<Object[]> list = new ArrayList<>();
where <>
at the right is also called diamond operator.