I'm reading 《Effective Java》, and it says we can use the codes below to make contents of an array not modifiable:
private static final Thing[] PRIVATE_VALUES = { ... };
public static final Thing[] values() {
return PRIVATE_VALUES.clone();
}
However, we know that both the arrays(the original and copied) will have the same reference to each of the element.So how can the method above avoids contents of an array being modified.I really doubt it.Could anyone help me.Thanks very much.
There is no way to make the elements of an array not modifiable. That is why some people pass unsafe methods a clone() of the array or pass the elements as an unmodifiable List.
Object[] original = new Object[]{ ... some objects ... }
Object[] clone = original.clone()
The original and the clone are now two different containers with the same objects (contents) in them.
The elements (what is in each array index) in the original will not be changed now even if the clone elements are changed. However, objects referenced in the array (what is in each array element) can still have their state changed.
Now, if your array is all primitives:
int[] original = {1,2,3,4,5}
int[] clone = original.clone()
Then the elements in original are not modifiable and also immutable.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With