Java language

Java Defensive copying

Copy mutable input before retaining it and return a copy instead of exposing internal mutable state. A primitive array clone suffices for its primitive elements; nested mutable values require a suitable deeper copying policy.

Formal Syntax & Structure

java syntaxjava
this.counts = counts.clone();

Working Example

Example Snippetjava
final class DailyCounts {    private final int[] counts;    DailyCounts(int[] counts) {        if (counts == null) throw new IllegalArgumentException("missing counts");        this.counts = counts.clone();        for (int count : this.counts) {            if (count < 0) throw new IllegalArgumentException("negative count");        }    }    public int[] counts() { return counts.clone(); }    public int size() { return counts.length; }}public class Main {    public static void main(String[] args) {        int[] input = {4, 8};        DailyCounts day = new DailyCounts(input);        input[0] = 90;        int[] exposed = day.counts();        exposed[1] = 99;        System.out.println(day.counts()[0]);        System.out.println(day.counts()[1]);    }}
Java Reference