Why String class is immutable even though it has a non -final field called “hash”

前端 未结 5 1776
故里飘歌
故里飘歌 2021-02-02 11:23

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

5条回答
  •  爱一瞬间的悲伤
    2021-02-02 11:32

    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

    1. If an object is changed from holding a reference to some particular immutable object to holding a reference to a different object with identical semantic content, such a change shouldn't affect the observable state of the object holding the reference, but if it turns out the supposedly-identical object wasn't really identical, bad things can happen, especially if the object supposedly holding the reference was assumed to be substitutable for other semantically-identical objects.
    2. Even if there aren't any mistakes in which objects are "identical", there may still be a danger that objects which appear identical to a thread which makes a substitution may not appear identical to other threads. This scenario isn't likely to occur, but if it does occur the effects may be very bad.

    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.

提交回复
热议问题