使用缓存时不可变 class
Immutable class while using a cache
在浏览 JCIP
时,我遇到了下面被认为是 Immutable
的代码片段。但是提供的解释让我感到困惑。
OneValueCache wouldn't be immutable without the copyOf calls in the constructor and getter. Arrays.copyOf was added as a convenience in
Java 6; clone would also work.
OneValueCache
的 state vars
本身 Immutable
与 final
和 BigInteger
本身 immutable
不一样吗?如果 OneValueCache
的状态已经是 Immutable
,为什么我们需要 Arrays.copyOf
?
class OneValueCache {
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;
public OneValueCache(BigInteger i,
BigInteger[] factors) {
lastNumber = i;
lastFactors = Arrays.copyOf(factors, factors.length);
}
public BigInteger[] getFactors(BigInteger i) {
if (lastNumber == null || !lastNumber.equals(i))
return null;
else
return Arrays.copyOf(lastFactors, lastFactors.length);
}
}
final
适用于 lastFactors
,但不适用于 lastFactors
的元素。如果方法直接返回 lastFactors
而没有复制它,调用者可以毫无问题地修改 lastFactors
的元素,更改 OneValueCache
的内部状态。通过复制操作,返回的数组是最终变量的副本,任何修改都会修改数组的副本,而不是不可变实例。
在浏览 JCIP
时,我遇到了下面被认为是 Immutable
的代码片段。但是提供的解释让我感到困惑。
OneValueCache wouldn't be immutable without the copyOf calls in the constructor and getter. Arrays.copyOf was added as a convenience in Java 6; clone would also work.
OneValueCache
的 state vars
本身 Immutable
与 final
和 BigInteger
本身 immutable
不一样吗?如果 OneValueCache
的状态已经是 Immutable
,为什么我们需要 Arrays.copyOf
?
class OneValueCache {
private final BigInteger lastNumber;
private final BigInteger[] lastFactors;
public OneValueCache(BigInteger i,
BigInteger[] factors) {
lastNumber = i;
lastFactors = Arrays.copyOf(factors, factors.length);
}
public BigInteger[] getFactors(BigInteger i) {
if (lastNumber == null || !lastNumber.equals(i))
return null;
else
return Arrays.copyOf(lastFactors, lastFactors.length);
}
}
final
适用于 lastFactors
,但不适用于 lastFactors
的元素。如果方法直接返回 lastFactors
而没有复制它,调用者可以毫无问题地修改 lastFactors
的元素,更改 OneValueCache
的内部状态。通过复制操作,返回的数组是最终变量的副本,任何修改都会修改数组的副本,而不是不可变实例。