Languages
[Edit]
EN

Java - immutable ArrayList in Java

4 points
Created by:
Kate_C
22360

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 it is the list is only covered by class - list is not copied that makes solution very light.

Quick solution:

Collections.unmodifiableList(list);

 Full example:

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

public class Example {

    public static main(String[] args) {

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

        immutableList.add("four");
    }
}

 

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