English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this program, you will learn to use toArray() to convert a list to an array, and use asList() in Java to convert an array to a list.
import java.util.ArrayList; import java.util.Arrays; import java.util.List; public class ListArray { public static void main(String[] args) { List<String> list = new ArrayList<String>(); list.add("a"); list.add("b"); String[] array = new String[list.size()]; list.toArray(array); System.out.println(Arrays.toString(array)); } }
When running the program, the output is:
[a, b]
In the above program, we have a string list list. To convert the list to an array, we first created a string array array with a size equal to list.size().
Then, we only use the list's toArray() method to convert list items to array items.
import java.util.Arrays; import java.util.List; public class ArrayToList { public static void main(String[] args) { String[] array = {"a", "b"}; List<String> list = Arrays.asList(array); System.out.println(list); } }
When running the program, the output is:
[a, b]
In the above program, we have a string array array. To convert the array to a list, we use the Arrays.asList() method and store it in the list list.