Re: what the benefit is by using annotation, like "@Immutable" ?
Peter Duniho wrote
And, also presumably, this is the same thinking that led to the code
in which those unfortunate strings with a hash code of 0 always wind
up getting recalculated no matter what (because otherwise, one would
need a flag, separate from the hash code field, which could wind up
out-of-sync with the hash code field absent synchronization, such as
"volatile"???as discussed previously in this thread).
Mike Schilling wrote:
Or simply giving them an arbitrary different value for hashCode() (e.g.
1), which is vanishingly unlikely to create any problems. (Though it
does break the explicit contract of String.hashCode(), which would need
to be changed.)
I'm still not clear on what makes 1 or 42 or 17 or any other value
significantly "better" than 0. One might as well use 0, since likely the only
String with a hash to be recalculated each time in practice will be "", and as
others have pointed out, that one is very quick to recalculate.
"" is probably the single most common String to have a degenerate hash code.
The check for 0 cannot be eliminated, so all you'd save with the "1" hack
would be the very fast re-calculation of 0. Yes, for the rare cases others
than "" you might have a truly anomalous result, but code complexity and a
magic number for that must just not have seemed worth the benefit.
OTOH, you could keep the value of 0 for "" by picking a sentinel value
different from 0, say 1 or 17 or 42 or 23 or -1, initializing 'hash' to that
value and using it in the conditional within 'hashCode()'.
None of these things really matter. The only reason that the Implementors
even bothered to lazy-load the hash for String was the knowledge that Strings
would be incessantly allocated and only sometimes used as keys or other hash
sources. In the latter case, the overhead of the lazy calculation is quickly
masked, and incessant tweaking for the remaining 0.001% possible speedup is by
the wayside. The rest of us should not lazy-load hashes for immutable
instances anyway.
--
Lew