Languages
[Edit]
EN

Java - immutable ArrayList in Java

4 points
Created by:
Kate_C
19810

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
50 000 ad impressions - 449$
🚀
Get your tech brand or product in front of software developers.
For more information contact us:
Red dot
Dirask - friendly IT community for everyone.

❤️💻 🙂

Join