[英]Definition of a constant field in Bloch's Effective Java 2nd edition
Quote: 引用:
If a static final field has a mutable reference type, it can still be a constant field if the referenced object is immutable.
如果静态final字段具有可变引用类型,则如果引用的对象是不可变的,则它仍然可以是常量字段。
I'm not sure what this mean; 我不确定这是什么意思; can someone give an example of that?
有人可以给出一个例子吗?
An example that Josh is talking about would be List
, which is a mutable type ( add()
, remove()
, etc), but you can assign an immutable instance to it: Josh正在谈论的一个例子是
List
,它是一个可变类型( add()
, remove()
等),但你可以为它分配一个不可变的实例:
public static final List<String> NAMES = Collections.unmodifiableList( Arrays.asList("foo", "bar")); // immutable
By the way, a great example of something that looks like a constant, but isn't, is a Date
constant: 顺便说一下,一个看起来像常量但不是的常量的一个很好的例子是
Date
常量:
public static final Date EPOCH = new Date(0);
but then some code can do this: 但是一些代码可以做到这一点:
EPOCH.setTime(123456789); // oops!
Date
is mutable ! Date
是可变的 ! Everyone will see such a change. 每个人都会看到这样的变化。
In constrast with this is something like String
, which is immutable: 与此类似,就像
String
一样,它是不可变的:
public static final String NAME = "Agent Smith"; // immutable
You can have a mutable type with an immutable subtype: 您可以使用具有不可变子类型的可变类型:
class Mutable {} // Not immutable, because it can be extended.
final class Immutable extends Mutable {}
// Reference type is mutable, but referenced object is immutable.
static final Mutable CONSTANT = new Immutable();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.