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

Asked

Viewed 11,683 times

16

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 it before Arrays.asList, example:

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

What is the difference between the use of these methods?

  • 3

    According to the documentation, the first returns an immutable list, and the second returns only a changeable converted list. I just don’t know how far that list goes.

  • 6

    Now I read it better, Lisf.of returns a list that cannot have its structure modified, IE, is read-only, you can not add, remove or replace any of its items. Arrays.asList returns a fixed-size list based on the number of elements of the corresponding array, but this resulting list is not immutable, you can normally change its structure.

2 answers

11


Arrays.asList()

Returns a fixed-size list supported by the specified matrix. 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 List, Set, Map and Map.Entry immutable. 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 class Collections, like the unmodifiableXXX to create objects Collection Immutable. For example, if we want to create an Immutable List, we can use the method Collections.unmodifiableList.

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

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

List umListImutavelVazio = List.of();

List nonempty:

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

1

Complementing the another answer, there are several differences between these two methods (reference).

One has already been quoted: Arrays.asList returns a list that can be modified (but with caveats, see below), while List.of returns a list that nay can be modified:

// esta lista pode ser modificada (posso mudar elementos já existentes)
List<String> asList = Arrays.asList("maça", "laranja");
// mudando o elemento da posição zero
asList.set(0, "abacaxi"); // OK
System.out.println(asList); // [abacaxi, laranja]

// esta lista não pode ser modificada
List<String> listOf = List.of("maça", "laranja");
listOf.set(0, "abacaxi"); // Erro: java.lang.UnsupportedOperationException

However, it is worth remembering one detail: the list returned by Arrays.asList has fixed size, ie, I can only change the values of existing positions (as I did above with the method set). But if I want to add or remove elements, it will give error:

List<String> asList = Arrays.asList("maça", "laranja");
// qualquer método que mude o tamanho da lista dá erro
asList.add("banana"); // Erro: java.lang.UnsupportedOperationException
asList.remove(0); // Erro: java.lang.UnsupportedOperationException

Another difference is the treatment given for null values. Arrays.asList accepts null elements, while List.of nay:

// ok, pode ter null
List<String> asList = Arrays.asList("maça", "laranja", null);
System.out.println(asList); // [abacaxi, laranja, null]

// erro, não pode ter null
List<String> listOf = List.of("maça", "laranja", null); // NullPointerException

The same occurs when I check for a null element:

List<String> asList = Arrays.asList("maça", "laranja");
// pode verificar se contém elemento nulo
System.out.println(asList.contains(null)); // false

List<String> listOf = List.of("maça", "laranja");
// não pode verificar se contém elemento nulo
System.out.println(listOf.contains(null)); // NullPointerException

Another difference is that when we pass an array to these methods, Arrays.asList keeps a reference to the original array, and therefore changes in one reflect on the other. Already with List.of this does not happen, and changes in one do not reflect in the other:

String[] frutas = { "maça", "laranja" };
List<String> asList = Arrays.asList(frutas);
System.out.println(asList); // [maça, laranja]

// modificações no array refletem na lista
frutas[0] = "abacaxi";
System.out.println(asList); // [abacaxi, laranja]
// modificações na lista refletem no array
asList.set(1, "banana");
System.out.println(frutas[1]); // banana


//-------------------------------------------
String[] frutas2 = { "maça", "laranja" };
List<String> listOf = List.of(frutas2);
System.out.println(listOf); // [maça, laranja]

// modificações no array NÃO refletem na lista
frutas2[0] = "abacaxi";
System.out.println(listOf); // [maça, laranja]

Finally, it is also worth mentioning Collections.unmodifiableList, that as well as List.of, returns a list that cannot be modified (set, add and remove launch UnsupportedOperationException), but the difference is that unmodifiableList accepts null values.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.