Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String immutability allows hashcode value to be cached

Among the many reasons to why Strings are immutable, one of the reasons is cited as

String immutability allows hashcode value to be cached.

I did not really understand this. What is meant by caching hashcode values? Where are these values cached? Even if Strings would have been mutable, this cached hashcode value could always be updated as required; so what's the big deal?

like image 310
Andy897 Avatar asked Jul 30 '26 13:07

Andy897


1 Answers

What is meant by caching hashcode values? Where are these values cached?

After the hash code is calculated, it is stored in a variable in String.
Looking at the source of String makes this clearer:

public final class String implements ... {
    ...
    /** Cache the hash code for the string */
    private int hash; // Default to 0

    ...

    public int hashCode() {
        int h = hash;
        if (h == 0 && ...) {
            ...
            hash = h;
        }
        return h;
    }

    ...
}

Even if Strings would have been mutable, this cached hashcode value could always be updated as required

True. But it would have to be recalculated / reset in every modification function. While this is possible, it's not good design.

All in all, the reason probably would've been better if it were as follows:

String immutability makes it easier to cache the hashcode value.

like image 148
Bernhard Barker Avatar answered Aug 01 '26 01:08

Bernhard Barker



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!