【发布时间】:2022-01-23 10:04:26
【问题描述】:
我正在尝试连接两个字符串,一个带有一些值的字符串,另一个带有空值。
例子:
String string1="Great"
String string2="";
并用 concat 函数和 + 运算符连接这两个字符串
例子:
String cat=string1.concat(string2)
String operator=string1+string2
根据我的理解,在 concat 函数中使用空字符串,因为 string2 为空,不会创建新的引用。但是在使用 + 运算符时,将在字符串池常量中创建一个新的引用。但是在下面的代码中,使用 + 运算符时不会创建新的引用。
public class Main {
public static void main(String[] args) {
String string1="Great",string2="";
String cat=string1.concat(string2);
if(string1==cat)
{
System.out.println("Same");
}
else
{
System.out.println("Not same");
}
String operator=string1+string2;
if(operator==string1)
System.out.println("Same");
else
System.out.println("Not same");
}
}
输出:
字符串 1:69066349
猫:69066349
一样
字符串1:69066349
接线员:69066349
不一样
从上面的代码中,由于它使用了 + 操作符,变量 : 操作符的引用应该引用新的内存,但它指向的是 string1 引用。请解释一下上面的代码。
【问题讨论】:
-
String.hashCode() 是字符串值的函数,而不是其地址
-
是的,但是我通过调试代码检查了地址引用。 hashCode 供我参考。
-
hashCode与这里的引用无关,只是字符串值的函数
-
没有它指向同一个引用,我通过调试检查了地址。我在问题中提到了它。仔细阅读问题。
标签: java string string-concatenation