1
String s = "abc";
String s4 = s + "";
System.out.println(s4 == s);
System.out.println(s4.equals(s));

这打印:


谁能解释一下为什么会这样?

4

2 回答 2

3
String s="abc"; // goes to string constants pool
String s4 = s +"" ;// has value "abc" but goes on heap and not in string constants pool
System.out.println(s4==s);//well,, the references are not equal. There are 2 diffrent instances with value="abc"
System.out.println(s4.equals(s)); // equals() checks for value and the values of both insatnces are equal.
于 2015-03-12T08:30:12.983 回答
1

这是您的代码,带有注释中的输出 -

String s="abc";
String s4 = s +"" ;
System.out.println(s4==s); //false
System.out.println(s4.equals(s)); //true  

第一个是false因为它正在检查s4and的引用s。由于这两个参考不同,因此评估为false. 这里==(相等)运算符,当应用于引用类型时,用于检查两个引用是否相同或不同。

equals()是由对象类中的每个引用类型实现的方法。您可以为自己的类覆盖 equals() 方法。

equals(s)方法用于检查两个对象是否有意义地相等。对于String类,有意义的等于意味着两个比较字符串相同,但它们的引用可能不同。String类已经覆盖了该equals()方法,因此您不需要equals()自己覆盖该方法。

现在为了理解字符串池的概念,请考虑以下代码片段 -

String s5 = s;
System.out.println(s5); //abc
System.out.println(s5==s); //true
System.out.println(s5.equals(s)); //true

这里s5==s评估为真。因为s5没有引用新的 String 对象。它引用池中现有的 String 对象(即 - 引用的“abc” s) 。string现在两个参考s5s4相等。在最后一条语句中 s5 和 s 有意义地等于,因此s5.equals(s)计算为true

希望它会有所帮助。
非常感谢。

于 2015-03-12T07:21:56.783 回答