Java Lists — Unmodifiable vs Immutable

Luiz Gustavo De O. Costa
3 min readJun 13, 2021

Working with Lists is a common task in Java, but this task should be done carefully whether the unmodifiable or immutable is required.

Change
Change

1. Why?

This article covers the change inside the elements of the List in order to avoid problems, for instance: Where is the element nth? Why did the element have one value and now has another value?

2. Benefits?

Retain the data as is, and don’t allow any element change, if required or a man in the middle.

3. Definition

1.1. Unmodifiable

The term unmodifiable means that the structure of the List itself cannot be altered[1].

1.2. Immutable

If the elements in the List are mutable (which is very common in Java), you can change the contents of the elements themselves. You cannot, however, alter the List so that it refers to any different elements, nor can you add or remove any elements.[1]

3. Diagram

I wrote these classes in order to explain the behaviour, even though the article [1], has a simple example only with String.

Class diagram

4. Playing with immutable

The intent to test the immutable list is to create two elements of Podcast’s and then change the Country of the first and check if the value inside the Playlist was changed.

Even though the podcast is declared as final inside the Playlist the value is changed, since the elements are mutable 😉. Take a look at the line 20, the set method, should be evicted as a good practice.

Remember, the List.of factory, line 15 returns an immutable collection, but allows element change.

5. Playing with unmodifiable

In this second scenario, the structure cannot be altered and any change will not be fired.

Let’s create 2 songs from Guardians of the Galaxy Vol. I added it to the playlist. Pay attention to line 8, since the variable is not declared as final, a new association could be done, but the reference will be another, line 20, then the music variable remains unmodifiable.

6. Recommendations

Avoid to use new ArrayList<>(), if possible use factories such as Arrays.asList, List.Of, List.copy, Collections.unmodifiableList to avoid time to find out where the element is.

7. Environment

openJDK 11, JUnit5, lombok

8. References

--

--

Luiz Gustavo De O. Costa

Hey friend!! I’m Luiz Gustavo, a Java developer and I’m here to learn and write about Java, tests and good practices