gpt4 book ai didi

java - 由于字符串根据内容存储在字符串常量池中(当我们用 = 初始化它时),因此在这种情况下为什么 s1 == s3 false

转载 作者:行者123 更新时间:2023-12-02 12:14:57 24 4
gpt4 key购买 nike

当字符串根据内容存储在字符串常量池中时(当我们用 = 初始化它时),在这种情况下为什么 s1 == s3 false ;

public static void main(String[] args) {
String s1 = "ABC:5";
String s2 = "ABC:5";
String s3 = "ABC:"+s1.length();
String s4 = "check";
System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.length());
System.out.println(s1.hashCode());
System.out.println(s2.hashCode());
System.out.println(s3.hashCode());
System.out.println(s4.hashCode());
}

甚至 s1 、 s2 和 s3 的哈希码也是相同的;

最佳答案

@Pritam Banerjee 的回答并不完全正确。

// both declarations are using the same object in memory
String s1 = "ABC:5"; // s1 == s1
String s2 = "ABC:5"; // s2 == s1

// this one creates at the beginning StringBuilder
String s3 = "ABC:" + s1.length(); // s3 != s1
String s4 = new StringBuilder().append("ABC:").append(s1.length()).toString();
// s4 != s1 && s4 != s3 this is what happens in byte code for s3

// the last case
String s5 = "ABC:" + "5"; // s5 == s1, because compiler knows exact value before compiling

它的字节码:

  public StringBuilderTest();
Code:
0: aload_0
1: invokespecial #1 // Method java/lang/Object."<init>":()V
4: return

public static void main(java.lang.String[]);
Code:
0: ldc #2 // String ABC:5
2: astore_1
3: ldc #2 // String ABC:5
5: astore_2
6: new #3 // class java/lang/StringBuilder
9: dup
10: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
13: ldc #5 // String ABC:
15: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/Stri
ngBuilder;
18: aload_1
19: invokevirtual #7 // Method java/lang/String.length:()I
22: invokevirtual #8 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
25: invokevirtual #9 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
28: astore_3
29: new #3 // class java/lang/StringBuilder
32: dup
33: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V
36: ldc #5 // String ABC:
38: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/Stri
ngBuilder;
41: aload_1
42: invokevirtual #7 // Method java/lang/String.length:()I
45: invokevirtual #8 // Method java/lang/StringBuilder.append:(I)Ljava/lang/StringBuilder;
48: invokevirtual #9 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
51: astore 4
53: ldc #2 // String ABC:5
55: astore 5
57: return
}

您可以阅读有关声明字符串及其相等性的更多信息 here

关于java - 由于字符串根据内容存储在字符串常量池中(当我们用 = 初始化它时),因此在这种情况下为什么 s1 == s3 false,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46259215/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com