3

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?

3
  • 1
    Have you check this one out: stackoverflow.com/questions/10576939/…? Commented Oct 10, 2013 at 20:35
  • Yes, I already did. Does not help much. Thanks anyways. Commented Oct 10, 2013 at 20:38
  • They talked about performance considerations. This was enough reason for me to justify caching. Commented Oct 10, 2013 at 20:42

1 Answer 1

5

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.