Sobes.tech
Junior — Middle

How can you make an array returned via a getter unmodifiable from outside?

sobes.tech AI

Answer from AI

To prevent the array returned via a getter from being modified externally, you should return a copy of the internal array rather than the array itself. Otherwise, external code will get a reference to the same array and will be able to modify its contents.

Example:

public class MyClass {
    private int[] data;

    public MyClass(int[] data) {
        this.data = data.clone(); // copy when saving
    }

    public int[] getData() {
        return data.clone(); // return a copy to protect internal state
    }
}

This approach guarantees that changes to the array obtained through the getter will not affect the internal state of the object.

How can you make an array returned via a getter… - sobes.tech