Re: How equals method works in StringBuffer?
- From: "Oliver Wong" <owong@xxxxxxxxxxxxxx>
- Date: Thu, 31 Aug 2006 13:54:07 GMT
"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
.
- References:
- How equals method works in StringBuffer?
- From: swornavidhya_m
- Re: How equals method works in StringBuffer?
- From: Chris Smith
- Re: How equals method works in StringBuffer?
- From: Jeffrey Schwab
- How equals method works in StringBuffer?
- Prev by Date: Re: How equals method works in StringBuffer?
- Next by Date: Best way to get user input from the console window?
- Previous by thread: Re: How equals method works in StringBuffer?
- Next by thread: Unescaping Unicode code points in a Java string
- Index(es):
Relevant Pages
|
|