Immutable Arrays in Java: Beyond Primitive Types
When working with arrays in Java, you may encounter situations where you require an immutable data structure that prevents the modification of elements. Although marking arrays as final can restrict referencing changes, it doesn't prevent internal element manipulation.
For true immutability, consider alternatives to primitive arrays. One option is to leverage Lists, which offer an extensive range of immutable implementations. For instance, using the Collections.unmodifiableList method, you can create an immutable version of a mutable list.
Consider the following example:
<code class="java">final int[] array = new int[] {0, 1, 2, 3}; array[0] = 42; // Attempt to modify an element</code>
In this case, even though the array reference itself is final, you can still modify the individual elements, resulting in a change to the array's contents.
To achieve immutability, you can use the following code:
<code class="java">List<Integer> items = Collections.unmodifiableList(Arrays.asList(0, 1, 2, 3));</code>
By converting the mutable list to an immutable list using Collections.unmodifiableList, you ensure that the elements remain unchangeable, protecting you from unintended alterations.
The above is the detailed content of How to Achieve True Immutability with Arrays in Java: Beyond Primitive Types?. For more information, please follow other related articles on the PHP Chinese website!