English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
Dans ce programme, vous apprendrez à utiliser toArray() pour convertir une liste en tableau et à utiliser asList() de Java pour convertir un tableau en liste.
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]
Dans le programme ci-dessus, nous avons une liste de chaînes de caractères list. Pour convertir la liste en tableau, nous avons d'abord créé un tableau de chaînes de caractères array, dont la taille est égale à list.size().
Then, we simply use the list.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.