1

I know that declaring an array final does not make it immutable.

I can however define a wrapper class that functions like an immutable array, e.g.

public class ImmutableIntArray {
    private int[] array;

    public ImmutableIntArray(int[] array) {
        this.array = (int []) array.clone();
    }

    public int get(int i) {
        return array[i];
    }

    public int length() {
        return array.length;
    }

    public static void main(String[] args) {
        ImmutableIntArray a = new ImmutableIntArray(new int[]{1, 2, 3});

        for (int i = 0; i < a.length(); ++i)
            System.out.println(a.get(i));
    }
}

This approach seems elegant to me, however, it seems like quite an obvious approach that I'm surprised I haven't seen anyone else apply it. Why shouldn't this be for example part of a standard library somewhere? Am I making any mistakes about this definition, so that my class is in fact mutable?

I believe the same approach would work for any Object which is immutable, that I could even define it using generics, i.e. an ImmutableArray<T> class.

6
  • Probably because people uses List ;) Commented Sep 13, 2013 at 23:56
  • you are simply removing some "privileges" to your array, you cannot add something to the array. In my opinion, you are just block some features to the user, but at the base there is still a mutable object. maybe I am wrong. Commented Sep 13, 2013 at 23:57
  • Igor, are Lists immutable? (is just a question because I don't know) Commented Sep 13, 2013 at 23:58
  • 1
    Your approach is throughly used, is extrange you didn't see it before. Commented Sep 13, 2013 at 23:59
  • Normal lists, such as ArrayList are mutable. But calling Collections.unmodifiableList(myListInstance) does the same as your class. It returns a List (it implements the interface) where mutators throw unsupportedOperationException. So is the same approach as yours. A good design. Commented Sep 14, 2013 at 0:02

1 Answer 1

4

You are reinventing the wheel. You can have the same result using Collections#unmodifiableList(..).

Collections.unmodifiableList(Arrays.asList(yourArray)); 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.