Arrays.asList in Java Collection

Introduction

In this article, we will understand the usages of Arrays.asList() method and why it returns an unmodifiable List.

Overview

Arrays.asList() method returns a list which can't be modified structurally, We use structurally as we can change an object state inside that list using the List's set method describe in the below code.

list.set(index, element);

It is not possible to add elements to the list or remove elements from the list. The reason is that the list is backed by the array, and the array is not the collection also the size of the array may not change.

Arrays.asList is a bridge between array and collection.

Usages of Arrays.asList()

  1. The Arrays.asList method allows you, to pass data to a method that expects a Collection
    /**A method that expects a collection*/
    static void display(List strings) { ... }
    
    public static void main(String...s)
    {
        String array[] = new String[] { "Java", "PHP", "PYTHON" };
    
        /**Pass the array (as a list) to the method*/
        display(Arrays.asList(array));
    }
    
  2. For example, you want to convert an array to Set. There is two way to do that.
     String array[] = new String[] { "Java", "PHP", "PYTHON" };
     Set set = new HashSet();
     for (String s : array) 
      {
        set.add(s);
       }
     By using the Arrays.asList method, this can be done more conveniently.
    Set set = new HashSet(Arrays.asList(array));

Summary

  1. Arrays.asList() convert an array and return a structurally unmodified list, which means we can not add or remove elements from it but we can modify objects inside the List.
  2. It is a bridge between array and collection.
  3. It is the opposite of the Collection.toArray() method which converts the collection object to array.