ArrayList imutável em Java

ArrayList imutável em Java

1. Visão geral

Este tutorial rápido mostraráhow to make an ArrayList immutable com o JDK principal, com Guava e finalmente com Apache Commons Collections 4.

Este artigo faz parte dethe “Java – Back to Basic” series aqui no exemplo.

Leitura adicional:

Coletar um fluxo Java em uma coleção imutável

Aprenda a coletar Java Streams em coleções imutáveis.

Read more

Introdução aos Imutáveis

Uma introdução rápida e prática à biblioteca Immutables - usada para gerar objetos imutáveis ​​através do uso de anotações.

Read more

Java - Obter item / elemento aleatório de uma lista

Um guia rápido e prático para escolher um item aleatório de uma lista em Java.

Read more

2. Com o JDK

Primeiro, o JDK fornece uma boa maneira de obter uma coleção não modificável de uma existente:

Collections.unmodifiableList(list);

A nova coleção não deve mais ser modificável neste momento:

@Test(expected = UnsupportedOperationException.class)
public void givenUsingTheJdk_whenUnmodifiableListIsCreated_thenNotModifiable() {
    List list = new ArrayList(Arrays.asList("one", "two", "three"));
    List unmodifiableList = Collections.unmodifiableList(list);
    unmodifiableList.add("four");
}

3. Com goiaba

O Guava fornece uma funcionalidade semelhante para criar sua própria versão deImmutableList:

ImmutableList.copyOf(list);

Da mesma forma - a lista resultante não deve ser modificável:

@Test(expected = UnsupportedOperationException.class)
public void givenUsingGuava_whenUnmodifiableListIsCreated_thenNotModifiable() {
    List list = new ArrayList(Arrays.asList("one", "two", "three"));
    List unmodifiableList = ImmutableList.copyOf(list);
    unmodifiableList.add("four");
}

Observe que esta operação irá realmentecreate a copy of the original list, não apenas uma visualização.

O Guava também fornece um construtor - ele retornará oImmutableList de tipo forte em vez de simplesmenteList:

@Test(expected = UnsupportedOperationException.class)
public void givenUsingGuavaBuilder_whenUnmodifiableListIsCreated_thenNoLongerModifiable() {
    List list = new ArrayList(Arrays.asList("one", "two", "three"));
    ImmutableList unmodifiableList = ImmutableList.builder().addAll(list).build();
    unmodifiableList.add("four");
}

4. Com o Apache Collections Commons

Por fim, o Commons Collection também fornece uma API para criar uma lista não modificável:

ListUtils.unmodifiableList(list);

E, novamente, a modificação da lista resultante deve resultar em umUnsupportedOperationException:

@Test(expected = UnsupportedOperationException.class)
public void givenUsingCommonsCollections_whenUnmodifiableListIsCreated_thenNotModifiable() {
    List list = new ArrayList(Arrays.asList("one", "two", "three"));
    List unmodifiableList = ListUtils.unmodifiableList(list);
    unmodifiableList.add("four");
}

5. Conclusão

Este tutorial ilustra comocreate an unmodifiable List out of an existing ArrayList facilmente usando o núcleo JDK, Google Guava ou Apache Commons Collections.

A implementação de todos esses exemplos e trechos de códigocan be found over on Github - este é um projeto baseado em Maven, portanto, deve ser fácil de importar e executar como está.