java – What is the difference between Arrays.asList and List.of?

Question:

Studying Java 9, I saw a new method that works with collections: List.of , example:

List<String> frutas = List.of("maça", "laranja");

I've used Arrays.asList before, example:

List<String> frutas = Arrays.asList("maça", "laranja");

What is the difference between using these methods?

Answer:

Arrays.asList()

Returns a fixed-size list supported by the specified array. This method acts as a bridge between array-based and collection-based APIs.

Example:

package com.exemplo;

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

public class ArrayExemplo {
  public static void main (String args[]) {

  // cria um array de strings
  String a[] = new String[]{"abc","def","fhi","jkl"};

  List list1 = Arrays.asList(a);

  // imprime a lista
  System.out.println("A lista é:" + list1);
 }
}

List.of

Oracle introduced some convenient methods to create immutable List , Set , Map and Map.Entry . These utility methods are used to create empty or non-empty collection objects .

In Java SE 8 and earlier, we can use the utility methods of the Collections class, such as unmodifiableXXX to create Immutable Collection objects. For example, if we want to create an Immutable List, we can use the Collections.unmodifiableList method.

However, these Collections.modifiableXXX methods are very tedious and verbose . To overcome these flaws, Oracle has added some useful methods to the List , Set and Map interfaces.

The List and Set interfaces have " of() " methods to create an immutable empty or non-empty List or Set as shown below:

List umListImutavelVazio = List.of();

List not empty:

List umListImutavel = List.of("um","dois","tres");
Scroll to Top