使用复制构造函数正确实现不可变的类
/** 来 自 时代Java - nowjava.com **/ class MyClass { private final IntHolder valueHolder; public MyClass(int value) { this.valueHolder = new IntHolder(value); } public MyClass(IntHolder holder) { // Must make a copy of holder parameter this.valueHolder = new IntHolder(holder.getValue()); } /* Rest of the code goes here... */ }/*来自 时代Java公众号*/ class IntHolder { private final int value; private int halfValue = Integer.MAX_VALUE; public IntHolder(int value) { this.value = value; } public int getValue() { return value; } public int getHalfValue() { // Compute half value if it is not already computed if (this.halfValue ==