Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Java

Defensive collection copying

Copy a list in the constructor and in `getRoles()` so callers cannot modify the list stored in a DTO. A `final` field alone does not provide that protection.

Version: Java SE 21

Syntax

private final List<String> roles;

RolesDto(List<String> roles) {
    this.roles = new ArrayList<>(roles);
}

public List<String> getRoles() {
    return new ArrayList<>(roles);
}

Defensive collection copying protects an object's state from changes through a shared reference. In a data transfer object (DTO), the constructor stores new ArrayList<>(roles) rather than keeping the caller's list. Each call to getRoles() returns a fresh, mutable list. Both copies preserve element order. A final field cannot be reassigned to another list, but final does not stop operations such as add or set on the list itself.

new ArrayList<>(roles) makes a shallow copy: the lists are separate objects, but they refer to the same elements. This is enough for String because strings are immutable. With mutable elements, a change to an element's state can be visible through both lists. If that state needs protection too, copy it on input and output or use immutable element types.

If callers do not need to edit the result and null is not allowed, store List.copyOf(roles) in the constructor and return that list directly. Later changes to the source list are not reflected in the result, and copyOf need not allocate a fresh instance. Result mutators throw UnsupportedOperationException; a null source or element causes NullPointerException. The result is still shallow. By contrast, Collections.unmodifiableList(roles) creates an unmodifiable view, not a copy: source-list changes remain visible through it.

Examples

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

public class Main {
    static final class RolesDto {
        private final List<String> roles;

        RolesDto(List<String> roles) {
            this.roles = new ArrayList<>(roles);
        }

        public List<String> getRoles() {
            return new ArrayList<>(roles);
        }
    }

    public static void main(String[] args) {
        List<String> input = new ArrayList<>(List.of("reader"));
        RolesDto dto = new RolesDto(input);
        input.add("admin");

        List<String> returned = dto.getRoles();
        returned.set(0, "owner");

        System.out.println(input);
        System.out.println(returned);
        System.out.println(dto.getRoles());
    }
}

Result

[reader, admin]
[owner]
[reader]

`input.add("admin")` changes only the input list, and `returned.set(0, "owner")` changes only the copy from the first `getRoles()` call. The second call still returns `[reader]`.

Related lessons

  • Java · Lesson 10 · Advanced · Version: 2

Sources