Question

It appears in java.lang.String.java, that Java will only generate the hashcode, and then store it, after a call to hashcode(), but why not just make the hashcode in the constructor?

The relevant code:

if (h == 0 && count > 0) {
    int off = offset;
    char val[] = value;
    int len = count;

    for (int i = 0; i < len; i++) {
        h = 31*h + val[off++];
    }

    hash = h;
}

could for the most part be placed in the constructor.

Was it helpful?

Solution

Why spend time generating a hash code that most likely will not be used? Most strings are constructed, used and then garbage collected without the hashcode() ever being called.

OTHER TIPS

Joshua Bloch call this practice 'racy single-check'.

Jeremy Manson has excellent explanation of why it's done and why it'safe: on his blog

In essence, at construction time you save some time by skipping calculating hash code. In multithreaded environment you'll pay for this back because multiple thread potentially could do the same calculation.

This is not really the correct forum for this and the question will likely be closed. You can try asking in programmers.stackexchange.com.

One reason could be that computing hashCode is not cheap and it is required only in some cases.

2 reasons:

1) Computing hashCode() is not cheap: is an O(n) complexity on the string's length, so better do it only when need it.

and:

2) String instances are immutable: Since they never change, you always compute hashCode() at most one time.

There is no benefit when placing it in the constructor. But there's a downside when it would be in the constructor. When hashCode for a String is never called then computation was done for nothing. And when you call hashCode() then it is calculated once in both cases - just in different places and time.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top