Defensive Copying for Immutability in Java


Defensive copying is a technique where you create copies of mutable input/return data to ensure the immutability of your classes.

Source Code

public final class ImmutableStudent {
    private final List subjects;

    public ImmutableStudent(List subjects) {
        this.subjects = new ArrayList(subjects); // Defensive Copy
    }

    public List getSubjects() {
        return Collections.unmodifiableList(subjects); // Return an immutable list
    }
}
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments