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

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

王林
Release: 2023-08-27 12:01:03
forward
710 people have browsed it

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()
Copy after login

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)
Copy after login

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 + " ");
      }
   }
}
Copy after login

Output

This will produce the following result-

List: [1, 2, 3, 4]
1 2 3 4
1 2 3 4
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template