首页 > 解决方案 > 为什么用一些字符串文字与其他最终的字符串变量连接来初始化字符串变量?

问题描述

此代码打印“B”。它不应该什么都不打印吗?我读过连接(+)就像执行一个方法,因此它会产生新的字符串,但这里不是这样。我认为这可能是因为 def 变量是最终的,但是带有 def 变量的复合运算符的工作方式不同......

String abcdef = "abcdef";
final String def = "def";
String a = "abc";
a += def;
String b = "abc" + def;
String c = "abc";
c = c + def;
if(abcdef == a) {
    System.out.println("A");
}
if(abcdef == b) {
    System.out.println("B");
}
if(abcdef == c) {
    System.out.println("C");
}

标签: java

解决方案


我假设您意识到您应该将 Strings 与equalsand not进行比较==。但是,请查看字符串的标识 hashCodes。 abcdefb有相同的。这就是为什么它们是相等的使用== 它们从内部缓存中引用相同的对象。

String abcdef = "abcdef";
final String def = "def";
String a = "abc";
a += def;
String b = "abc" + def;
String c = "abc";
c = c + def;
System.out.println("a = " + System.identityHashCode(a)
        + " abcdef = " + System.identityHashCode(abcdef));
System.out.println("b = " + System.identityHashCode(b)
+ " abcdef = " + System.identityHashCode(abcdef));
System.out.println("c = " + System.identityHashCode(c)
+ " abcdef = " + System.identityHashCode(abcdef));
if (abcdef == a) {
    System.out.println("A");
}
if (abcdef == b) {
    System.out.println("B");
}
if (abcdef == c) {
    System.out.println("C");
}

印刷

a = 925858445 abcdef = 798154996
b = 798154996 abcdef = 798154996
c = 681842940 abcdef = 798154996
B

推荐阅读