With subscript, we can instantly fetch the data elements stored in the memory. So to leverage the power of subscript, we may need to convert a list into an array.

Therefore in this programming example, we will learn to convert a Java List (or ArrayList) into an Array.

Method 1: Using Loop

The conventional method of converting a list into an array is to declare an array of the same size as the list and fill the data by iterating through the list items.

We can implement this in Java by the following steps:

  1. Declare an array of the same type and size as the List.
  2. Iterate through the list items and assign them to the array at the corresponding index.

Here is the implementation of the steps in Java:

Output:

Array: 1 2 3 4

The time complexity of this method is O(n) because we are explicitly looping through the given ‘n’ items of the list and adding them to the array.

This method works for both primitive and reference types of data.

Method 2: Using List.toArray()

According to StackOverflow, toArray() method of the List class returns an array of the items in the list.

Syntax in Java 8:

Syntax in Java 11:

Here is an example in Java, in which we are converting an integer list to an integer array:

Output:

Array: 1 2 3 4

This method works only with the referenced data types. If you want to use it with primitive’s data then use its wrapper class (e.g., Integer instead of int as shown in the above example).

In this tutorial, we learned how to convert a list into an array in Java programming language. Comment below if you know some other methods.

Leave a Reply

4 − two =