Andy897
Andy897

Reputation: 7133

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?

Upvotes: 3

Views: 774

Answers (1)

Bernhard Barker
Bernhard Barker

Reputation: 55629

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.

Upvotes: 5

Related Questions