Hi,
Is the below class immutable:
final class MyClass {
private final int[] array;
public MyClass(int[] array){
this.array = array;
}
}
Hi,
Is the below class immutable:
final class MyClass {
private final int[] array;
public MyClass(int[] array){
this.array = array;
}
}
No it is not because the elements of the array can still be changed.
int[] v1 = new int[10];
MyClass v2 = new MyClass(v1);
v1[0] = 42; // mutation visible to MyClass1
There is no way to make an array immutable. That is there is no way to keep any client code from setting or removing or adding items to the array.
Here is a truly immutable alternative:
private static class MyClass
{
private List<Integer> list;
private MyClass(final int[] array)
{
final List<Integer> tmplist = new ArrayList<Integer>(array.length);
for (int i : array)
{
tmplist.add(array[i]);
}
this.list = Collections.unmodifiableList(tmplist);
}
}
My two cents regarding immutability rules (which I retained from reading Effective Java - a great book!):
"Immutability" is a convention between the programmer and himself. That convention may be more or less enforced by the compiler.
Instances of a class are "immutable" if they do not change during the normal course of the application code execution. In some cases we know that they do not change because the code actually forbids it; in other cases, this is just part of how we use the class. For instance, a java.util.Date
instance is formally mutable (there is a setTime()
method on it) but it is customary to handle it as if it were immutable; this is just an application-wide convention that the Date.setTime()
method shall not be called.
As additional notes:
String
is documented to be immutable (that's what the Javadoc says). But if you look at the source code, you will see that a String
instance contains a private field called hash
which may change over time: this is a cache for the value returned by hashCode()
. We still say that String
is immutable because the hash
field is an internal optimization which has no effect visible from the outside.final
), if the programmer wishes so hard enough. Not that it is a good idea: it may break assumptions used by other pieces of code using the said instance. As I said, immutability is a convention: if the programmer wants to fight himself, then he can, but this can have adverse side-effects on productivity...MyClass
instance ? There is no generic answer to that question.