English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List (List)

Java Queue (queue)

Java Map collection

Java Set collection

Java Input Output(I/O)

Java Reader/Writer

Java other topics

Java program is the conversion between list (ArrayList) and array (Array)

Comprehensive Java Examples

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.

Example1Convert list to array

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.

Example2: Convert Array to List

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.

Comprehensive Java Examples