StringBuilder .equals Java [英] StringBuilder .equals Java

查看:81
本文介绍了StringBuilder .equals Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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
    }

}

输出是

And the output is

Test
Test
false
false

在.equals上快速提问。

Just have a quick question on .equals.

无论对象内容如何, .equals 只有当两个对象引用都指向同一个对象时才返回true?

Regardless of the object content, does .equals return true only if both the object references point to the same object ?

编辑:现在我理解关于 .equals 的部分,但为什么第2行和第3行也不会返回 true

EDIT : Now I understand the part about the .equals but why does Line 2 and Line 3 also not return true ?

编辑:我相信 == 查看引用变量的地址,因此s1和s2不能相等。如果我的假设不对,请更正我

EDIT : I believe == looks at the reference variable's address and so s1 and s2 cannot be equal.correct me if my assumption is not right

推荐答案

是, StringBuilder不会覆盖Object的.equals()函数,这意味着两个对象引用不相同,结果为false。

Yes, StringBuilder does not override Object's .equals() function, which means the two object references are not the same and the result is false.

对于 StringBuilder ,你可以使用 s1.toString()。equals(s2.toString())

对于编辑,您在两个不同的String对象上调用 == 运算符。 == 运算符将返回false,因为对象不同。要比较字符串,您需要使用 String.equals() String.equalsIgnoreCase()

For your edit, you're calling the == operator on two different String objects. The == operator will return false because the objects are different. To compare Strings, you need to use String.equals() or String.equalsIgnoreCase()

这与你之前遇到的问题相同

It's the same problem you were having earlier

这篇关于StringBuilder .equals Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆