问题
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.
回答1:
You are reinventing the wheel. You can have the same result using Collections#unmodifiableList(..).
Collections.unmodifiableList(Arrays.asList(yourArray));
来源:https://stackoverflow.com/questions/18796886/defining-my-own-immutable-array-in-java