Can we convert a Java list to array?



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)

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.

Example

Following is the example showing the usage of toArray() 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) {
      List<String> list = new ArrayList<>(Arrays.asList("A","B","C", "D"));
      System.out.println("List: " + list);
      Object[] items = list.toArray();
      for (Object object : items) {
         System.out.print(object + " ");
      }
      System.out.println();
      String[] characters = list.toArray(new String[0]);
      for (String string : characters) {
         System.out.print(string + " ");
      }
   }
}

Output

This will produce the following result −

List: [A, B, C, D]
A B C D
A B C D

Advertisements