Convert Array to List in Java

1. Introduction

Converting an array to a List in Java is a common operation that facilitates easier manipulation and processing of data stored in the array. Java provides several ways to perform this conversion, leveraging the utilities in the java.util package. This blog post will demonstrate how to convert a Java array to a List using both the Arrays.asList() method and the Collections.addAll() method.

2. Program Steps

1. Create an array of elements.

2. Convert the array to a List using the Arrays.asList() method.

3. Convert the array to a List using the Collections.addAll() method.

4. Display the Lists to illustrate the conversion.

3. Code Program

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class ArrayToList {
    public static void main(String[] args) {
        // Creating an array
        String[] fruitsArray = {"Apple", "Banana", "Cherry"};

        // Method 1: Converting array to List using Arrays.asList()
        List<String> list1 = Arrays.asList(fruitsArray);

        // Method 2: Converting array to List using Collections.addAll()
        List<String> list2 = new ArrayList<>();
        Collections.addAll(list2, fruitsArray);

        // Displaying the Lists
        System.out.println("List created using Arrays.asList(): " + list1);
        System.out.println("List created using Collections.addAll(): " + list2);
    }
}

Output:

List created using Arrays.asList(): [Apple, Banana, Cherry]
List created using Collections.addAll(): [Apple, Banana, Cherry]

Explanation:

1. The program starts by importing necessary classes from the java.util package, which provides utility methods and classes for working with collections.

2. An array fruitsArray is created containing several elements. This array will be converted to a List in two different ways.

3. The first conversion method uses Arrays.asList(), which takes the array as an argument and returns a fixed-size list backed by the specified array. This means changes to the array reflect in the list and vice versa. However, the size of the list cannot be modified (i.e., elements cannot be added or removed).

4. The second conversion method involves creating a new instance of an ArrayList and then populating it with elements from the array using Collections.addAll(). This method provides a fully modifiable list with no linkage to the original array.

5. The lists created by both methods are then printed to the console, showing that the array has been successfully converted to a List in both cases.

6. This example highlights two approaches to converting an array to a List in Java, each with its characteristics and use cases.

Comments