Java Arrays asList()

In this guide, you will learn about the Arrays asList() method in Java programming and how to use it with an example.

1. Arrays asList() Method Overview

Definition:

The Arrays.asList() method returns a fixed-size list backed by the specified array. This means that changes to the returned list are reflected in the original array, and vice-versa.

Syntax:

static <T> List<T> asList(T... a)

Parameters:

- a: The array by which the list will be backed.

Key Points:

- The returned list is serializable and implements RandomAccess.

- The list does not support add, remove, and set operations if the underlying array cannot be resized.

- It provides a convenient way to convert an array to a List.

2. Arrays asList() Method Example


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

public class AsListExample {
    public static void main(String[] args) {
        String[] stringArray = {"A", "B", "C"};

        List<String> stringList = Arrays.asList(stringArray);

        System.out.println("List content: " + stringList);

        // Trying to add an element to the list will throw an exception
        // stringList.add("D");  // Uncommenting this will throw UnsupportedOperationException

        // Modifying an element in the list reflects in the array
        stringList.set(1, "Z");
        System.out.println("Modified List content: " + stringList);
        System.out.println("Array content: " + Arrays.toString(stringArray));
    }
}

Output:

List content: [A, B, C]
Modified List content: [A, Z, C]
Array content: [A, Z, C]

Explanation:

In the example, we first create a string array with three elements. We then convert this array to a list using Arrays.asList(). Any changes made to this list (like using the set method) are reflected back in the original array as demonstrated in the output. However, operations like add or remove, which would require resizing the array, are not supported on the returned list and will throw an UnsupportedOperationException.

Comments