Can we convert a list to an Array in Java?

JavaObject Oriented ProgrammingProgramming

We can convert a list into an array easily using its toArray() method.

Syntax

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

Returns an array containing all of the elements in this list in proper sequence (from first to last element); the runtime type of the returned array is that of the specified array. If the list fits in the specified array, it is returned therein. Otherwise, a new array is allocated with the runtime type of the specified array and the size of this list.

Type Parameter

  • − The runtime type of an array.

Returns

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

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.

Example

Following example shows how to convert a list into array.

package com.tutorialspoint;

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

public class CollectionsDemo {
   public static void main(String[] args) {
      // Create a list object
      List<String> list = new ArrayList<>(Arrays.asList("A", "B", "C"));

      // print the list
      System.out.println(list);
      String[] array = list.toArray(new String[0]);
      for (String string : array) {
         System.out.print(string + " ");
      }
   }
}

Output

This will produce the following result −

[A, B, C]
A B C
raja
Updated on 09-May-2022 11:33:34

Advertisements