问题描述
这是Java Concurrency in Practice中的一句话
不可变对象和有效不可变对象之间有什么区别?
该类的实例不可扩展,且其字段均为final
并且自身不可变,它们是不可变的.
由于其方法的详细信息而无法更改其字段的类的实例实际上是不可变的.例如:
final class C {
final boolean canChange;
private int x;
C(boolean canChange) { this.canChange = canChange; }
public void setX(int newX) {
if (canChange) {
this.x = newX;
} else {
throw new IllegalStateException();
}
}
}
C
的某些实例实际上是不可变的,而有些则不是.
另一个例子是零长度数组.它们实际上是不可变的,即使它们的包含类不是可证明的不可变的,因为它们中没有元素可以更改.
Joe-E使用验证程序来证明某些类仅允许不可变的实例.带有 Immutable
标记接口,并将某些类(如String
(由于其char[]
不会逸出,因此实际上是不可变的))作为不可变的.
This is a sentence from Java Concurrency in Practice
What are the differences between immutable and effectively immutable objects?
Instances of a class that is not extensible and whose fields are all final
and themselves immutable are immutable.
Instances of a class whose fields cannot be mutated because of details of its methods are effectively immutable. For example:
final class C {
final boolean canChange;
private int x;
C(boolean canChange) { this.canChange = canChange; }
public void setX(int newX) {
if (canChange) {
this.x = newX;
} else {
throw new IllegalStateException();
}
}
}
Some instances of C
are effectively immutable and some are not.
Another example is zero-length arrays. They are effectively immutable even though their containing class is not provably immutable since there is no element of them which can be changed.
Joe-E uses a verifier to prove that some classes only allow for immutable instances. Anything marked with the Immutable
marker interface are checked and certain classes like String
(effectively immutable since its char[]
does not escape) are grandfathered in as immutable.
Joe-E: A Security-Oriented Subset of Java says
这篇关于不可变对象和有效不可变对象之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!