class strb
{
static public void main(String...string)
{
StringBuilder s1 = new StringBuilder("Test");
StringBuilder s2 = new StringBuilder("Test");
System.out.println(s1);
System.out.println(s2);
System.out.println(s1==s2);
System.out.println(s1.equals(s2)); //Line 1
System.out.println(s1.toString()==s2.toString()); //Line 2
if(s1.toString()==s2.toString())System.out.println("True"); //Line 3
}
}
输出是
Test
Test
false
false
对 .equals 有一个简短的问题。
无论对象内容如何,.equals
是否只有在两个对象引用都指向同一个对象时才返回 true ?
EDIT :现在我了解了关于 .equals
的部分,但是为什么第 2 行和第 3 行也不返回 true
?
编辑:我相信 ==
会查看引用变量的地址,因此 s1 和 s2 不能相等。如果我的假设不正确,请纠正我
最佳答案
是的,StringBuilder没有覆盖Object的.equals()函数
,也就是说两个对象引用不一样,结果为false。
对于StringBuilder
,你可以使用s1.toString().equals(s2.toString())
对于您的编辑,您在两个不同的 String 对象上调用 ==
运算符。 ==
运算符将返回 false,因为对象不同。要比较字符串,您需要使用 String.equals()
或 String.equalsIgnoreCase()
这和你之前遇到的问题一样
关于java - StringBuilder .equals Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18565701/