How to create List of Arrays in Java

We know how to create list of integer or list of string using List interface. But today let us see how to list of arrays using List interface in Java.

We will be using ArrayList for this task.

import java.util.ArrayList;
import java.util.List;

public class Tech4Humans {

	public static void main(String[] args) {
		
		//declaring a new list of arrays
		List<Integer[]> integerArrayList = new ArrayList<Integer[]>();
		
		//initializing arrays
		Integer integerArray1[] = {10,20,30};
		Integer integerArray2[] = {11,22,33,44};
		Integer integerArray3[] = {100,200,1000,500};
		
		//adding arrays to arraylist
		integerArrayList.add(integerArray1);
		integerArrayList.add(integerArray2);
		integerArrayList.add(integerArray3);
		
		//traversing list of arrays
		for(Integer[] tempArray : integerArrayList) {
			for(int i=0; i<tempArray.length; i++) {
				System.out.print(tempArray[i]+" ");
			}
			System.out.println();
		}
	}

}

Output

10 20 30 
11 22 33 44 
100 200 1000 500

Let us try to understand how the arrays are stored internally in ArrayList will help of the diagram.

In the above diagram we can see that each slot of arraylist is pointing toward the array or we can say each slot stores the address of array.

So when we traverse through the arraylist, the pointer goes to 0th index and goes to the address stored at that index. The address will be of array. Now we can traverse through that array. Similarly pointer will go to next index of Arraylist and then to array address and so on.

Leave a Comment