Sobes.tech
Junior — Middle

How can immutability of a list that is a class field be ensured?

sobes.tech AI

Answer from AI

To ensure the immutability of a list that is a class field in Java, you can:

  • Use Collections.unmodifiableList() to wrap a mutable list so that external users cannot modify it.
  • Initialize the field with a list that is inherently immutable, for example, using List.of() (Java 9+).
  • Make the field private final and do not provide methods that modify the list.

Example:

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

public class MyClass {
    private final List<String> items;

    public MyClass(List<String> input) {
        this.items = Collections.unmodifiableList(input);
    }

    public List<String> getItems() {
        return items;
    }
}

Thus, external code cannot modify the contents of the list through the class field.