Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make a contents of an array not modifiable in Java

Tags:

java

arrays

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.

like image 593
tuan long Avatar asked Mar 25 '26 00:03

tuan long


1 Answers

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.

like image 66
The Coordinator Avatar answered Mar 26 '26 13:03

The Coordinator



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!