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

11

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

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

I already used Arrays.asList , for example:

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

What's the difference between using these methods?

    
asked by anonymous 06.10.2017 / 14:46

1 answer

8

Arrays.asList ()

Returns a fixed-length 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 has introduced some convenient methods for creating List , Set , Map and Map.Entry objects immutable. These utility methods are used to create empty or non-empty collection objects .

In Java SE 8 and earlier, we can use the Collections class's utility methods, such as unmodifiableXXX to create Collection immutable 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 shortcomings, Oracle added some utility methods to the List , Set and Map interfaces.

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

List umListImutavelVazio = List.of();

List not empty:

List umListImutavel = List.of("um","dois","tres");
    
07.10.2017 / 17:44