Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/305.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 字符串不变性允许缓存哈希代码值_Java_String_Hashcode - Fatal编程技术网

Java 字符串不变性允许缓存哈希代码值

Java 字符串不变性允许缓存哈希代码值,java,string,hashcode,Java,String,Hashcode,字符串不可变的原因很多,其中一个原因是 字符串不变性允许缓存哈希代码值 我真的不明白这一点。缓存hashcode值意味着什么?这些值缓存在哪里?即使字符串是可变的,这个缓存的hashcode值也可以根据需要随时更新;那有什么大不了的 缓存hashcode值意味着什么?这些值缓存在哪里 计算哈希代码后,它存储在String中的变量中 查看String的源代码可以更清楚地说明这一点: public final class String implements ... { ... /**

字符串不可变的原因很多,其中一个原因是

字符串不变性允许缓存哈希代码值

我真的不明白这一点。缓存hashcode值意味着什么?这些值缓存在哪里?即使字符串是可变的,这个缓存的hashcode值也可以根据需要随时更新;那有什么大不了的

缓存hashcode值意味着什么?这些值缓存在哪里

计算哈希代码后,它存储在
String
中的变量中
查看
String
的源代码可以更清楚地说明这一点:

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

    ...
}
即使字符串是可变的,这个缓存的hashcode值也可以根据需要进行更新

对。但必须在每个修改函数中重新计算/重置。虽然这是可能的,但这不是一个好的设计

总之,如果是这样的话,原因可能会更好:

字符串不变性使得缓存hashcode值更容易


你查过这个了吗?是的,我已经查过了。没有多大帮助。无论如何,谢谢。他们谈到了性能方面的考虑。这对我来说已经足够证明缓存的合理性了。