我知道Immutable对象比可变对象提供了几个优点,比起它们比可变对象更易于推理,它们没有随时间变化的复杂状态空间,我们可以自由地传递它们,它们可以制作安全的哈希表键等.所以我的问题是不可变对象的缺点是什么?
引自Effective
Java:
The only real disadvantage of immutable classes is that they require a
separate object for each distinct value. Creating these objects can be
costly,especially if they are large. For example,suppose that you
have a million-bit BigInteger and you want to change its low-order
bit:
BigInteger moby = ...;
moby = moby.flipBit(0);
The flipBit method
creates a new BigInteger
instance,also a million bits long,that
differs from the original in only one bit. The operation requires time
and space proportional to the size of the BigInteger
. Contrast this to
java.util.BitSet
. Like BigInteger
,BitSet
represents an arbitrarily
long sequence of bits,but unlike BigInteger
,BitSet
is mutable. The
BitSet
class provides a method that allows you to change the state of
a single bit of a millionbit instance in constant time.
阅读Item 15: Minimize mutability的完整项目