开发者

java StringBuffer and String Comparision

Why String.equls() returns true but Stringbuilder.equals() returns false?

    StringBuffer sb1 = new StringBuffer("Amit");
    StringBuffer sb2= new StringBuffer("Amit");
    St开发者_JAVA技巧ring ss1 = "Amit";
    String ss2 = "Amit";

System.out.println(sb1.equals(sb2)); //returns false
System.out.println(ss1.equals(ss2)); //returns true

Thx


StringBuffer does not override Object's equals() method, and thus, it returns true only when a StringBuffer object is compared with itself.

public boolean equals(Object obj) {
    return (this == obj);
}

To compare two StringBuffers based on their contents, do something like this:

sb1.toString().equals(sb2.toString());


StringBuffer does not define equals method, so Object's equals method is used, which only returns true if it's the same object. You can do

sb1.toString().equals(sb2.toString())

if you want to compare them as Strings


StringBuffer sb1 = new StringBuffer("Amit");
StringBuffer sb2= new StringBuffer("Amit");
String ss1 = "Amit";
String ss2 = "Amit";

System.out.println(sb1.equals(sb2)); //returns false
System.out.println(ss1.equals(ss2)); //returns true

In the first case sb1.equals(sb2), sb1 and sb2 will have two different addresses because it does not override the equals() method. If you really want to do a comparison that returns you true is

sb1.toString().equals(sb2.toString())
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜