Home  >  Article  >  Java  >  How to Ensure Immutability for Primitive Arrays in Java?

How to Ensure Immutability for Primitive Arrays in Java?

DDD
DDDOriginal
2024-10-28 12:34:01865browse

How to Ensure Immutability for Primitive Arrays in Java?

Immutable Arrays in Java

The primitive array type in Java does not offer immutability. Declaring an array as final merely protects the reference to the array from being reassigned, but does not prevent modifications to individual array elements.

To enforce immutability for an array of primitives, you must consider using an alternative data structure.

Unmodifiable List as an Alternative

An immutable alternative to primitive arrays is using the Collections.unmodifiableList() method to create an unmodifiable list backed by the array elements. This method returns a wrapper list that prevents any modifications to its contents.

<code class="java">List<Integer> items = Collections.unmodifiableList(Arrays.asList(0, 1, 2, 3));</code>

Once the unmodifiable list is created, any attempt to modify its elements will result in an UnsupportedOperationException. This ensures that the elements of the array remain unchanged while still allowing access to their values through the list interface.

The above is the detailed content of How to Ensure Immutability for Primitive Arrays in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn