Any type which doesn't give you any means to change the data within it is immutable - it's as simple as that. Yes, all the primitive wrapper types are immutable1, as is String
. UUID http://download.oracle.com/javase/6/docs/api/java/util/UUID.html, URL http://download.oracle.com/javase/6/docs/api/java/net/URL.html and URI http://download.oracle.com/javase/6/docs/api/java/net/URI.html are other examples.
虽然Calendar
and Date
内置 Java API 中的许多类型都是可变的乔达时间 http://joda-time.sf.net是不可变的——在我看来,这是oneJoda Time 更容易使用的原因。如果一个对象是不可变的,您可以在代码中的其他地方保留对它的引用,而不必担心其他代码段是否会进行更改 - 更容易reason关于你的代码。
1 by which I mean java.lang.Integer
etc. As noted elsewhere, the Atomic*
classes are mutable, and indeed have to be in order to serve their purpose. There's a difference in my mind between "the standard set of primitive wrapper classes" and "the set of classes which wrap primitive values".
您可以非常轻松地编写自己的可变包装类:
public class MutableInteger
{
private int value;
public MutableInteger(int value)
{
this.value = value;
}
public int getValue()
{
return value;
}
public void setValue(int value)
{
this.value = value;
}
}
正如你所看到的,什么也没有本质上包装类是不可变的 - 只是标准的类是designed不可变,因为不提供任何方法来更改包装值。
请注意,这允许在装箱时重复使用同一对象,以获得通用值:
Integer x = 100;
Integer y = 100;
// x and y are actually guaranteed to refer to the same object
Integer a = 1000;
Integer b = 1000;
// a and b *could* refer to the same object, but probably won't