Home > Java > javaTutorial > How Do I Convert a Java List to an Array?

How Do I Convert a Java List to an Array?

Barbara Streisand
Release: 2024-12-19 15:30:13
Original
795 people have browsed it

How Do I Convert a Java List to an Array?

How to Convert a List to an Array in Java

To convert a List to an array in Java, you can use either of the following methods:

Foo[] array = list.toArray(new Foo[0]);
Copy after login
Foo[] array = new Foo[list.size()];
list.toArray(array);
Copy after login

These methods only work for arrays of reference types. For primitive type arrays, you must use the traditional approach:

List<Integer> list = ...;
int[] array = new int[list.size()];
for(int i = 0; i < list.size(); i++) array[i] = list.get(i);
Copy after login

Best Practice

It is recommended to use the first method, list.toArray(new Foo[0]), for converting lists to arrays. This eliminates the need to specify the size of the array in advance and is more efficient in modern Java.

The above is the detailed content of How Do I Convert a Java List to an Array?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template