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

How to Ensure Immutability for Primitive Arrays in Java?

DDD
Release: 2024-10-28 12:34:01
Original
980 people have browsed it

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template