Immutable Arrays in Java

Java is a good language, but some aspects are problematic. Here is one caveat: the final modifier. I wish final’s application in preventing overriding, overloading, and inheriting classes used a different name: I am discussing only final where used in constants. I use final often but work to dissociate it from C++’s final modifier. When applied to mutable types, final breaks:

public static void main(String args[]) {
    final int amfinal[] = {0, 0, 0, 0};
    final[2] = 5;
}

No problem here, at least not syntactically. But this is problematic for modern OOP implementation (and data hiding).

public class ImmutableArray<T> implements Iterable<T> {
	private final T[] item;
	public static <V> ImmutableArray<V> from(V... array) {
		return new ImmutableArray<V>(array);
	}
	public static <V> ImmutableArray<V> of(V array[]) {
		return new ImmutableArray<V>(array);
	}
	private ImmutableArray(T[] array) {
		this.item = array;
	}
	public T get(int index) {
		return item[index];
	}
	public Iterator<T> iterator() {
		return null;
	}
	public int length() {
		return item.length;
	}
}

It is not perfect but works well for me. Have another solution? Comment!

Tags: , , , , , , , , ,

Leave a Reply