Home >Java >javaTutorial >In Java, how to convert a list to an array?

In Java, how to convert a list to an array?

王林
王林forward
2023-08-27 12:01:03707browse

In Java, how to convert a list to an array?

We can convert them into arrays using the toArray() method of List.

1. Use the toArray() method without parameters.

Object[] toArray()

Returns

an array containing all the elements in this list in correct order.

2. Use toArray() with an array of elements of a specific type.

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

Parameters

  • #a - the array in which to store the elements of this list (if large enough); otherwise, allocate an identical runtime for this purpose A new array of type.

Returns

an array containing the elements of this list.

Returns

an array containing the elements of this list. p>

Throws

  • ArrayStoreException - if the runtime type of the specified array is not a supertype of the runtime type of each element in this list.

  • NullPointerException - if the specified array is null.

Example

The following is an example showing the usage of toArray() method -

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<Integer> list = new ArrayList<>(Arrays.asList(1,2,3,4));
      System.out.println("List: " + list);
      Object[] items = list.toArray();
      for (Object object : items) {
         System.out.print(object + " ");
      }
      System.out.println();
      Integer[] numbers = list.toArray(new Integer[0]);
      for (Integer number : numbers) {
         System.out.print(number + " ");
      }
   }
}

Output

This will produce the following result-

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

The above is the detailed content of In Java, how to convert a list to an array?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete