Immutable array in Java

Viewed 121837

Is there an immutable alternative to the primitive arrays in Java? Making a primitive array final doesn't actually prevent one from doing something like

final int[] array = new int[] {0, 1, 2, 3};
array[0] = 42;

I want the elements of the array to be unchangeable.

15 Answers

As of Java 9 you can use List.of(...), JavaDoc.

This method returns an immutable List and is very efficient.

Implement java.util.function.IntUnaryOperator:

class ImmutableArray implements IntUnaryOperator {
  private final int[] array;
  ImmutableArray(int[] array) {
     this.array = Arrays.copyOf(array, array.length);
  }
  @Override
    public int applyAsInt(int index) {
    return array[index];
  }
}

Access the array: array[i] becomes immutableArray.applyAsInt(i).

  • I benchmarked primitive for loop retrieval with a modulus operation with 100_000_000 elements. The above PrimitiveArray took ~220ms; there was no significant difference with a primitive array. The same op on ArrayList took 480 ms, and the loading process took 21 seconds, depleted my heap space first try, and I had to increase this setting on the JVM. Loading of PrimitiveArray had taken 2 seconds.

iteration

  • if you want to iterate, implement Iterable and provide

    public java.util.PrimitiveIterator.OfInt iterator() { return Arrays.stream(array).iterator(); }

    This provides access to int nextInt method.

  • From PrimitiveIterator you also get method forEachRemaining(PrimitiveConsumer) which is helpful to replace an existing enhanced for loop.

  • Iterating manually with PrimitiveIterator.OfInt yielded performance of ~300ms.

Related