Re: How equals method works in StringBuffer?




"Jeffrey Schwab" <jeff@xxxxxxxxxxxxxxxx> wrote in message news:lQAJg.1904$lk6.205@xxxxxxxxxxxxxxxxxxxxxxxxxxx
Chris Smith wrote:
<swornavidhya_m@xxxxxxxxxxx> wrote:
Hai,
In my following code, the output i obtained is: false. Whereas
my expectation for output is true. I need ur suggestions and ideas.

StringBuffer's equals method returns true only when a StringBuffer object is compared with itself. It returns false when compared with any other StringBuffer, even if the two contain the same characters. This is actually quite a sensible behavior.

Chris, would you mind elaborating a little? I would have expected:

sb1.equal(sb2) == sb1.toString().equal(sb2.toString())

StringBuffers use identity to determine equality, not contents. Strings use contents to determine equality.

That is, two strings are equal if they have the same content. So code like:

String str1 = new String("Hello");
String str2 = new String("Hello");
System.out.println(str1.equals(str2));
System.out.println(str1 == str2);

should print "true" followed by "false", because it's true that their contents are equal, but false that they are the same String.

StringBuffer did not override Object.equals(Object), and so the implementation of equals in StringBuffer is essentially:

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

- Oliver

.



Relevant Pages

  • Re: StringBuffer.equals and StringBuilder.equals gotcha
    ... The problem is StringBuffer.equals checks if two references point to ... I'd completely expect StringBuffer and String to never be equals, even if that forces an otherwise unnecessary toStringcall for some practical use cases. ... I'd think it is hardly a gotcha, when dealing a lot with equalslogic. ...
    (comp.lang.java.help)
  • Re: Teething troubles with JUnit
    ... >> Fell into the 'equality is not identity' trap. ... For String for instance equals returns true if the two ... the equals method asks whether these two objects can be ... they instead reverted to comparing the identity to at least ...
    (comp.lang.java.programmer)
  • Re: How equals method works in StringBuffer?
    ... my expectation for output is true. ... StringBuffer's equals method returns true only when a StringBuffer ... To compare the String objects that are produced by the StringBuffer ...
    (comp.lang.java.programmer)
  • Re: How equals method works in StringBuffer?
    ... Oliver Wong wrote: ... my expectation for output is true. ... It returns false when compared with any other StringBuffer, even if the two contain the same characters. ... StringBuffers use identity to determine equality, ...
    (comp.lang.java.programmer)
  • Re: StringBuffer equals method
    ... Andrew Thompson wrote: ... class TestEquals { ... method of StringBuffer and not String. ... String value inside the StringBuffer determines the equality (but ...
    (comp.lang.java.programmer)