I was reading through Item 15 of Effective Java by Joshua Bloch. Inside Item 15 which speaks about \'minimizing mutability\' he mentions five rules to make objects immutable. On
There are many situations in which it may be helpful for a class which is logically immutable have several different representations for the same observable state, and for instances of the class to be able to switch among them. The hashcode value that will be returned from a string whose hash field is zero will be the same as the value that would be returned if the hash field held the result of an earlier hashcode call. Consequently, changing the hash value from the former to the latter will not change the object's observable state, but will cause future operations to run faster.
The biggest difficulties with coding things in those ways are
Still, there can be some advantages to making substitutitions of immutable objects. For example, if a program will be comparing many objects which hold long strings and many of them, though separately generated, will be identical to each other, it may be useful to use a WeakDictionary
to build a pool of distinct string instances, and replace any string which is found to be identical to one in the pool with a reference to the pool copy. Doing that would cause many strings which are identical to be mapped to the same string, thus greatly accellerating any future comparisons that may be done between them. Of course, as noted it's very important that the objects are properly logically immutable, that the comparisons are done correctly. Any problems in that regard can turn what should be an optimization into a mess.