Creating an immutable version of a type using defensive copying.
suggest changeSome basic types and classes in Java are fundamentally mutable. For example, all array types are mutable, and so are classes like java.util.Date. This can be awkward when an immutable type is required.
One way to deal with this is to create an immutable wrapper for the mutable type. Here is a simple wrapper for an array of integers:
public class ImmutableIntArray {
private final int[] array;
public ImmutableIntArray(int[] array) {
this.array = array.clone();
}
public int[] getValue() {
return array.clone();
}
}
This class works by using defensive copying to isolate the mutable state (the int[]) from any code that might mutate it:
- The constructor uses
clone()to create a distinct copy of the parameter array. If the caller later changes the parameter array, that does not affect theImmutableIntArray. - The
getValue()method also usesclone()to create the array that is returned. If the caller were to change the result array, it would not affect the state of theImmutableIntArray.
We could also add methods to ImmutableIntArray to perform read-only operations on the wrapped array; e.g. get its length, get the value at a particular index, and so on.
Note that an immutable wrapper type implemented this way is not type compatible with the original type. You cannot simply substitute the former for the latter.