Can we convert an array to list and back in Java?


The List provides two methods to convert a List into Array.

1. Use toArray() method without parameter.

Object[] toArray()

Returns

An array containing all of the elements in this list in proper sequence.

2. Use toArray() with array.

<T> T[] toArray(T[] a)

Type Parameter

  • − The runtime type of the array.

Parameters

  • − The array into which the elements of this list are to be stored, if it is big enough; otherwise, a new array of the same runtime type is allocated for this purpose.

Returns

An array containing the elements of this list.

Throws

  • ArrayStoreException − If the runtime type of the specified array is not a supertype of the runtime type of every element in this list.

  • NullPointerException − If the specified array is null.

In order to convert an array to list we can use Arrays.asList() method to get the list containing all the elements of an array.

public static <T> List<T> asList(T... a)

Type Parameter

  • − The runtime type of the element.

Parameters

  • − The array by which the list will be backed.

Returns

A list view of the specified array.

Example

Following is the example showing the usage of toArray() and Arrays.asList() methods −

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      Integer[] array = {1, 2, 3, 4, 5};

      // array to List conversion
      List<Integer> list = new ArrayList<>(Arrays.asList(array));
      System.out.println("List: " + list);

      // list to array conversion
      Object[] items = list.toArray();
      for (Object object : items) {
         System.out.print(object + " ");
      }
      System.out.println();

      // list to array conversion
      Integer[] numbers = list.toArray(new Integer[0]);
      for (int number : numbers) {
         System.out.print(number + " ");
      }
   }
}

Output

This will produce the following result −

List: [1, 2, 3, 4, 5]
1 2 3 4 5
1 2 3 4 5

Updated on: 09-May-2022

144 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements