Home >Java >javaTutorial >In Java, how to convert a list to an array?
We can convert them into arrays using the toArray() method of List.
Object[] toArray()
an array containing all the elements in this list in correct order.
<T> T[] toArray(T[] a)
#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.
an array containing the elements of this list.
an array containing the elements of this list. p>
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.
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 + " "); } } }
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!