Languages
[Edit]
EN

Java - immutable ArrayList in Java

4 points
Created by:
Tomeriko
293

In this short article, we would like to how in Java create immutable List - read-only list.

This technique can be used with all classes that implements List interface. Main advantage of this approach is: the list is only covered by class - list is not copied that makes solution very fast.

Quick solution:

Collections.unmodifiableList(list);

 

Practical example

import java.util.Arrays;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;

public class Example {

    public static void main(String[] args) {

        List<String> list = new ArrayList<>(Arrays.asList("one", "two", "three"));
        List<String> immutableList = Collections.unmodifiableList(list);

        immutableList.add("four");
    }
}

Output:

Exception in thread "main" java.lang.UnsupportedOperationException
	at java.base/java.util.Collections$UnmodifiableCollection.add(Collections.java:1060)
	at Example.main(Example.java:13)

Note: in read-only list we are not able to do any modification.

Alternative titles

  1. Java - readonly ArrayList in Java
  2. Java - unmodifiable ArrayList in Java
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Java Collections - ArrayList

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

â€ïžđŸ’» 🙂

Join