简体   繁体   English

使用缓存时不可变 class

[英]Immutable class while using a cache

While going through JCIP , I came across the below code snippet which was considered as Immutable .在通过JCIP时,我遇到了以下被认为是Immutable的代码片段。 However the explanation provided makes me confused.然而,提供的解释让我感到困惑。

OneValueCache wouldn't be immutable without the copyOf calls in the constructor and getter.如果没有构造函数和 getter 中的 copyOf 调用,OneValueCache 就不会是不可变的。 Arrays.copyOf was added as a convenience in Java 6; Arrays.copyOf 为方便起见在 Java 6 中添加; clone would also work.克隆也可以。

Aren't the state vars of OneValueCache themselves Immutable with final and BigInteger being itself immutable ? state vars OneValueCache不是Immutable的,而finalBigInteger本身是immutable的吗? Why do we need to have Arrays.copyOf if the state of OneValueCache is already Immutable ?如果 OneValueCache 的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);
}
}

The final applies to lastFactors , but not to the elements of lastFactors . final适用于lastFactors ,但不适用于lastFactors的元素。 If the methods returned lastFactors directly without copying it, the caller could modify the elements of lastFactors without any problems, changing the internal state of OneValueCache .如果方法直接返回lastFactors而不复制它,调用者可以毫无问题地修改lastFactors的元素,改变 OneValueCache 的内部OneValueCache With the copy operations, the returned arrays are copies of the final variable, and any modifications will modify the copy of the array, not the immutable instance.通过复制操作,返回的 arrays 是最终变量的副本,任何修改都会修改数组的副本,而不是不可变的实例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM