Explain Codes LogoExplain Codes Logo

Immutable array in Java

java
immutable-arrays
java-9
data-integrity
Alex KataevbyAlex Kataev·Feb 23, 2025
TLDR

To create an "immutable array" in Java, domesticate an array with a List and make it cozy within a Collections.unmodifiableList():

List<String> unmodifiableList = Collections.unmodifiableList(new ArrayList<>(Arrays.asList("x", "y", "z")));

This constructs a read-only List habitat, putting a stopper on structural modifications. However, the contained objects can still run wild, if they are mutable.

Also, Java 9 says "present"

For those at the Java 9 house-party or later, we have party tricks like List.of and similar flicks from Set and Map interfaces for generating immutable collections:

List<String> immutableList = List.of("a", "b", "c"); // Party-goer list. Not accepting more entries!

Deep Dive: Introduction&Possible hiring

Unmodifiable vs Immutable: long-lost twins separated at birth

It's essential to distinguish between unmodifiable and immutable. Unmodifiable list is the party bouncer stopping uninvited guests, whereas immutable implies the location and guest-list remain as is. Zilch change!

Defensive copying: Copycats aren't always bad

When aiming for undisputed immutability, copy the original array like a pro con-artist. This defensive copy prevents unsolicited changes:

public ImmutableArray(T[] items) { this.array = Arrays.copyOf(items, items.length); // Break the mold after use, no more copies allowed! }

Secret Libraries: The Restricted Section

Step into the utility libraries like Guava's ImmutableList or Apache Commons Lang ImmutablePair for making arrays immutable. They are the Hogwarts of immutable arrays.

Performance considerations: Speed vs Integrity

Cloning arrays is like photocopying documents - useful but resource-consuming. Especially when dealing with large arrays, consider reusing immutable empty arrays or invent lazy copying mechanisms.

Advanced patterns: The skeleton key

Final does not mean final

Declaring an array final is akin to driving on the highway and never stopping. It keeps you going, but it doesn't stop you from changing lanes (element modification).

Immutable objects: The Untouchables

Immutable objects are like that antique vase your grandma has. Once made, they can't be changed. Just look and admire (and avoid breaking them).

Trust issues with client code

Expose an array to external clients and you are in for a wild ride. If arrays are not rock-solid immutable, your clients might still modify elements. Prepare for the unexpected.

The New Kid on the block: Java 9's Immutable Collections

Java 9 brings the Immutable Collections API which helps you create immutable collections. It's like a shortcut to your favorite cafe. Why go the long way when you can save so much time?

Less memory to lose

Reuse to refuse memory wastage

To save your precious memory, reuse immutable empty arrays:

public static final Object[] EMPTY_ARRAY = new Object[0]; // Anti-wastage campaign // Later in the code public Object[] getElements() { return elements.length == 0 ? EMPTY_ARRAY : elements.clone(); //Copycats are the last resort }

Immutable vs The World

List.of vs Collections.unmodifiableList

While List.of prevents structural changes and stops you from replacing elements, Collections.unmodifiableList only signs up for the former.

Immutable collections: Our superheroes

Using immutable collections is like a taste test. It might seem bland initially, but it's a flavor enhancer down the road. Embrace the exquisite taste of data integrity and predictable behavior in your application.