How can Java convert between Array and List?

In Java, you can convert a List to an Array using the toArray() method, or you can convert an Array to a List using the Arrays.asList() method. Here is a specific example code:

Convert a List to an Array.

import java.util.ArrayList;
import java.util.List;

public class ConvertListToArray {
    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add("Apple");
        list.add("Banana");
        list.add("Orange");

        String[] array = list.toArray(new String[list.size()]);

        for (String fruit : array) {
            System.out.println(fruit);
        }
    }
}

Convert Array to List.

import java.util.Arrays;
import java.util.List;

public class ConvertArrayToList {
    public static void main(String[] args) {
        String[] array = {"Apple", "Banana", "Orange"};

        List<String> list = Arrays.asList(array);

        for (String fruit : list) {
            System.out.println(fruit);
        }
    }
}

It’s important to note that the List returned by the Arrays.asList() method is a fixed-length List and does not support add or remove operations. If you need to manipulate the List, you can create a mutable List by using new ArrayList<>(Arrays.asList(array)).

bannerAds