public class Test {
public static void main(String[] args)
{
String s1 = "HELLO";
String s2 = "HELLO";
System.out.println(s1 == s2); // true
}
}
但是当我使用时:
public class Test {
public static void main(String[] args)
{
String s1 = new String("HELLO");
String s2 = new String("HELLO");
System.out.println(s1 == s2); // false
}
}
有人可以解释一下这里的区别吗?谢谢你!
在第一个例子中
String s1 = "HELLO";
String s2 = "HELLO";
的价值观s1
and s2
是编译时常量。因此,编译器只生成一个String
- 对象,保存值"HELLO"
并将其分配给两者s1
and s2
。这是一个特例公共子表达式消除 https://en.wikipedia.org/wiki/Common_subexpression_elimination,一个著名的编译器优化。因此s1 == s2
回报true
.
在第二个例子中,两个不同的String
s 是通过显式构造的new
。因此,根据语义,它们必须是单独的对象new
.
I created an Ideone demo https://ideone.com/1hnikI a while back that highlights some cases that show this behaviour.
您可以强制执行相同的操作String
是通过使用返回String::intern() https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/lang/String.html#intern():
String s1 = new String("HELLO").intern();
String s2 = new String("HELLO").intern();
System.out.println(s1 == s2); // will print "true";
Ideone demo https://ideone.com/CqbeqY
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)