Languages
[Edit]
EN

Java - immutable ArrayList in Java

4 points
Created by:
Kate_C
2872

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");
    }
}

 

Hey 👋
Would you like to know what we do?
  • Dirask is a friendly IT community for learners, professionals and hobbyists to share their knowledge and help each other in extraordinary easy way.
  • We welcome everyone,
    no matter what the experience,
    no matter how basic the question is,
    this community will help you.