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.
List items = Collections.unmodifiableList(Arrays.asList(0, 1, 2, 3));
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.
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3