Immutable ArrayList in Java

1. Overview

This quick tutorial will show how to make an ArrayList immutable with the core JDK, with Guava and finally with Apache Commons Collections 4.

This article is part of the “Java – Back to Basic” series here on Viet’s Blog.

2. With the JDK

First, the JDK provides a nice way to get an unmodifiable collection out of an existing one:

Collections.unmodifiableList(list);

The new collection should no longer be modifiable at this point:

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

2.1. With Java 9

Since Java 9, we can use a List<E>.of​(E… elements) static factory method to create an immutable list:

@Test(expected = UnsupportedOperationException.class)
public final void givenUsingTheJava9_whenUnmodifiableListIsCreated_thenNotModifiable() {
    final List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three"));
    final List<String> unmodifiableList = List.of(list.toArray(new String[]{}));
    unmodifiableList.add("four");
}

Notice how we have to convert the existing list into an array. This is because List.of(elements) accepts vararg parameters.

3. With Guava

Guava provides similar functionality for creating its own version of ImmutableList:

ImmutableList.copyOf(list);

Similarly – the resulting list should not be modifiable:

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

Note that this operation will actually create a copy of the original list, not just a view.

Guava also provides a builder – this will return the strong-typed ImmutableList instead of simply List:

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

4. With the Apache Collections Commons

Finally, Commons Collection also provides an API to create an unmodifiable list:

ListUtils.unmodifiableList(list);

And again, modifying the resulting list should result in an UnsupportedOperationException:

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

5. Conclusion

This tutorial illustrates how to easily create an unmodifiable List out of an existing ArrayList using either the core JDK, Google Guava or Apache Commons Collections.

The implementation of all these examples and code snippets can be found over on Github – this is a Maven-based project, so it should be easy to import and run as it is.

Related posts:

An Introduction to Java.util.Hashtable Class
ExecutorService – Waiting for Threads to Finish
Java Program to Find the Shortest Path from Source Vertex to All Other Vertices in Linear Time
Giới thiệu SOAP UI và thực hiện test Web Service
Truyền giá trị và tham chiếu trong java
Java – Write to File
Java Program to Check Whether a Directed Graph Contains a Eulerian Path
Java Program to Implement LinkedBlockingQueue API
Java Program to Implement Bloom Filter
Java Program to Implement the Monoalphabetic Cypher
Spring Boot - Database Handling
Java Program to Find Hamiltonian Cycle in an UnWeighted Graph
A Guide To UDP In Java
Hướng dẫn Java Design Pattern – Chain of Responsibility
Limiting Query Results with JPA and Spring Data JPA
Java Program to Implement Find all Cross Edges in a Graph
How to Delay Code Execution in Java
Java Program to Perform Insertion in a 2 Dimension K-D Tree
Java Program to Implement the Hungarian Algorithm for Bipartite Matching
ClassNotFoundException vs NoClassDefFoundError
Guide to Spring 5 WebFlux
Tính kế thừa (Inheritance) trong java
Registration – Password Strength and Rules
Adding Shutdown Hooks for JVM Applications
Hướng dẫn Java Design Pattern – Facade
HttpClient Timeout
Implementing a Binary Tree in Java
The Modulo Operator in Java
Java Program to Implement a Binary Search Algorithm for a Specific Search Sequence
Introduction to the Java NIO2 File API
Hướng dẫn sử dụng Printing Service trong Java
Java Program to Implement Sorted Doubly Linked List