How does string class does caching of Hashcode in java

后端 未结 2 826
滥情空心
滥情空心 2021-01-17 06:24
Here what is written in String API for Hashcode------
public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
                     


        
2条回答
  •  孤城傲影
    2021-01-17 06:32

    Each string object has a field called "hash". whenever hashcode() is called on string object, a local variable int h is declared with initial value of "hash" field. As initially hash value will be zero, hash value of this string is computed and stored in hash field. Henceforth whenever hashcode() is called on this string "hash" field value will be returned because it will be non-zero value and therefore not enter the if condition.

    As String is immutable, hash value can be cached. If it is mutable, then this caching strategy will not work.

    As your creating the two Strings using new, both will be different instances, and therefore each will have their own hash fields.

    public final class String
    implements java.io.Serializable, Comparable, CharSequence {
    /** The value is used for character storage. */
    private final char value[];
    
    /** Cache the hash code for the string */
    private int hash; // Default to 0
    ...
    public int hashCode() {
        int h = hash;
        if (h == 0 && value.length > 0) {
            char val[] = value;
    
            for (int i = 0; i < value.length; i++) {
                h = 31 * h + val[i];
            }
            hash = h;
        }
        return h;
    }
    }
    

提交回复
热议问题