0
0
JavaHow-ToBeginner · 3 min read

How to Use Arrays.asList in Java: Simple Guide

Use Arrays.asList(array) to convert an array into a fixed-size list in Java. This method returns a list backed by the original array, so changes to the list affect the array and vice versa.
📐

Syntax

The syntax for using Arrays.asList is simple:

  • Arrays.asList(array): Converts the given array to a fixed-size list.
  • The returned list is backed by the original array, so changes reflect both ways.
  • The list does not support adding or removing elements.
java
List<Type> list = Arrays.asList(array);
💻

Example

This example shows how to convert an array of strings to a list and print it.

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

public class Example {
    public static void main(String[] args) {
        String[] fruits = {"Apple", "Banana", "Cherry"};
        List<String> fruitList = Arrays.asList(fruits);

        System.out.println("List: " + fruitList);

        // Changing an element in the list also changes the array
        fruitList.set(1, "Blueberry");
        System.out.println("Modified array: " + Arrays.toString(fruits));
    }
}
Output
List: [Apple, Banana, Cherry] Modified array: [Apple, Blueberry, Cherry]
⚠️

Common Pitfalls

Common mistakes when using Arrays.asList include:

  • Trying to add or remove elements from the returned list causes UnsupportedOperationException because the list size is fixed.
  • Expecting the returned list to be a regular ArrayList that supports all modifications.
  • Modifying the original array or list affects the other since they share the same data.
java
import java.util.Arrays;
import java.util.List;

public class Pitfall {
    public static void main(String[] args) {
        String[] colors = {"Red", "Green", "Blue"};
        List<String> colorList = Arrays.asList(colors);

        // This will throw UnsupportedOperationException
        // colorList.add("Yellow");

        // Correct way to get a modifiable list:
        List<String> modifiableList = new java.util.ArrayList<>(colorList);
        modifiableList.add("Yellow");
        System.out.println(modifiableList);
    }
}
Output
[Red, Green, Blue, Yellow]
📊

Quick Reference

Summary tips for Arrays.asList:

  • Returns a fixed-size list backed by the array.
  • Supports set but not add or remove.
  • Changes to the list reflect in the array and vice versa.
  • Use new ArrayList<>(Arrays.asList(array)) for a modifiable list.

Key Takeaways

Arrays.asList converts an array to a fixed-size list backed by the array.
The returned list supports element changes but not adding or removing elements.
Modifying the list changes the original array and vice versa.
To get a fully modifiable list, wrap the result in a new ArrayList.
Avoid calling add or remove directly on the list from Arrays.asList to prevent errors.