In String source it looks like the hash code value (private int hashCode) is set only if the method public int hashCode() was called at least once. That means a different state. But will the hashCode be set in the following example:
String s = "ABC"; ?
Will
String s = "ABC";
s.hashCode();
help with subsequent comparisons performance?
Technically the string has changed. Some internal field is altered the first time you call hashCode()
.
But for all practical reasons the string is immutable. The value of the hash code doesn't change due to a call to hashCode()
, it simply isn't calculated until the first call. To any consumer of a string, the string is immutable. And that's what matters.
Immutable means that, from an outside perspective, the value of the object cannot be changed.
If hashCode
is being cached, the internal state of the object may be different after the first hashCode
call. But that call is read-only, and you can't change the value of the object as it appears to the outside world.
In other words, it's still the same string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With