简体   繁体   English

Bloch的Effective Java第2版中常量字段的定义

[英]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.

相关问题 约书亚布洛赫的有效Java中的等价方法 - Equals method in Joshua Bloch's Effective Java 有效的Java项目16(第2版) - Forwarding类是否仅用于允许重用? - Effective Java item 16 (2nd edition) - Is Forwarding class only used to allow re-use? Head First Java 第二版 - 第 118 页,第 5 章 - Head First Java 2nd Edition - Page 118, chapter 5 Enum类型,如Joshua Bloch在Effective Java中所述 - Enum Types as explained in Effective Java by Joshua Bloch 在C ++(VS2010)中使用Bloch的Effective Java实现类型安全的异构容器 - Implementing typesafe heterogeneous container from Bloch's Effective Java in C++ (VS2010) 什么是 Java 中的不可变值类? (Joshua Bloch 的有效 Java) - What is an immutable value class in Java? (Effective Java by Joshua Bloch) Joshua Bloch在有效的java中建议如何在Java中使用缓存哈希码? - how caching hashcode works in Java as suggested by Joshua Bloch in effective java? 有效的Java作者:Joshua Bloch:第1项 - 静态工厂方法 - Effective Java By Joshua Bloch: Item1 - Static Factory Method 为什么 Joshua Bloch 在 Effective Java 中使用 2*size + 1 来调整堆栈大小? - Why did Joshua Bloch use 2*size + 1 for resizing the stack in Effective Java? 在有效的Java第二项72中实现CountDownLatch的更好方法是什么? - What is the better way to implement CountDownLatch in effective java 2nd item 72?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM