Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/360.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_Jvm_Hashcode - Fatal编程技术网

Java字符串池存储

Java字符串池存储,java,string,jvm,hashcode,Java,String,Jvm,Hashcode,为什么hashcode与string对象相同 我试图了解字符串池是如何工作的。我浏览了很多网站,最后我更困惑了。让我在这里放下我的疑虑。有人帮我理解他们 class cov { public static void main(String[] args) { String s = "abc"; //Object on string pool System.out.println(s.hashCode()); String str =

为什么hashcode与string对象相同

我试图了解字符串池是如何工作的。我浏览了很多网站,最后我更困惑了。让我在这里放下我的疑虑。有人帮我理解他们

class cov {

    public static void main(String[] args) {
        String s = "abc"; //Object on string pool  
        System.out.println(s.hashCode());
        String str = new String("abc"); //This statement does two things  
        System.out.println(str.hashCode());


    }
}

字符串的
hashCode()
方法是根据其包含的字符计算的。如果两个String对象包含大小写相同且顺序相同的字符,则它们将具有相同的
hashCode()

String类具有一个
hashCode
方法,该方法从其内容而不是从其内存位置计算哈希代码。因此,如果两个字符串相同(但不一定相等),它们将具有相同的哈希代码


如果不是这种情况,像
HashSet
这样的结构将不可用-每一个新的
字符串
将不在该集中,即使已经添加了具有相同字符的
字符串。

下面是用于生成hashCode的源代码

public int hashCode() {
int h = hash;
if (h == 0) {
    int off = offset;
    char val[] = value;
    int len = count;

        for (int i = 0; i < len; i++) {
            h = 31*h + val[off++];
        }
        hash = h;
    }
    return h;
}
public int hashCode(){
int h=散列;
如果(h==0){
int off=偏移量;
char val[]=值;
int len=计数;
对于(int i=0;i

如其他答案所述,hashCode是从字符串的内容而不是它所在的位置生成的。e、 g heap stack或constant pool

@user272924 java中的所有对象都在堆上。@user272924:你的观点是?@user272924我不确定java中所有对象的哪些部分在堆上,或者你问的是什么。我发誓我将写一篇题为“java中的字符串没有什么特别之处”的博客文章@hovercraftfullofels我认为我们非常同意对方,但我的观点是,如果你像对待java中的任何其他对象一样对待
字符串
,那就没有什么意外了。这种困惑似乎来自于人们因为你提到的东西而认为它是特殊的。这个被标记为重复的问题是一个完全不同的问题!在关闭这个之前有人检查过吗?投票重新开放。