Is hash code of java.lang.String really cached?

耗尽温柔 提交于 2019-12-05 04:44:06
Sotirios Delimanolis

A String is meant to be immutable. As such, there is no point having to recalculate the hashcode. It is cached internally in a field called hash of type int.

String#hashCode() is implemented as (Oracle JDK7)

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;
}

where hash initially has a value of 0. It will only be calculated the first time the method is called.

As stated in the comments, using reflection breaks the immutability of the object.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!