Home | Contact Us | FAQ | Search & Site Map | Link to Us
Sign In | Join | Other 45 Sites in Network
HomeAnnouncementsWhite Papers
Discussion GroupsFirst AidDatabasesJavaBeansGUIJava 3DVirtual MachineCORBASecurityToolsGeneral
Java DirectoryOpen Source ProjectsSample Book ChaptersUser GroupsWeb Resources
Related Topics
Databases.NETMore Topics ...

Java Forum / General / September 2006

Tip: Looking for answers? Try searching our database.

How equals method works in StringBuffer?

Thread view: 
swornavidhya_m@yahoo.co.in - 31 Aug 2006 07:29 GMT
Hai,
       In my following code, the output i obtained is: false. Whereas
my expectation for output is true. I need ur suggestions and ideas.
       The code is as follows:
       Class stringBufferEqual
       {
           public static void main(String args[])
           {
                 StringBuffer s1 = new StringBuffer("Amit");
                 StringBuffer s2 = new StringBuffer("Amit");
                 System.out.println(s1.equals(s2));
           }
       }

       Awaiting for ur suggestions and ideas in advance.

M.Sworna Vidhya
Chris Smith - 31 Aug 2006 07:43 GMT
> 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.  However, the meaning of equals
is unfortunately not defined very well, and it is inconsistently used
across the Java API, so this is a bit confusing.

To compare the String objects that are produced by the StringBuffer
objects in their current state, use s1.toString().equals(s2.toString())
instead.

Signature

Chris Smith

Jeffrey Schwab - 31 Aug 2006 13:44 GMT
>> Hai,
>>         In my following code, the output i obtained is: false. Whereas
[quoted text clipped - 4 lines]
> 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())
Patricia Shanahan - 31 Aug 2006 14:50 GMT
>>> Hai,
>>>         In my following code, the output i obtained is: false. Whereas
[quoted text clipped - 8 lines]
>
>     sb1.equal(sb2) == sb1.toString().equal(sb2.toString())

The API documentation for StringBuffer lists "equals" as a method
inherited from Object, so I expect the same behavior as the Object
equals method.

Maybe it was done that way because you can always write
sb1.toString().equals(sb2.toString()) if that is what you mean.

Patricia
Oliver Wong - 31 Aug 2006 14:54 GMT
>>> Hai,
>>>         In my following code, the output i obtained is: false. Whereas
[quoted text clipped - 8 lines]
>
> 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
Jeffrey Schwab - 01 Sep 2006 01:45 GMT
>>>> Hai,
>>>>         In my following code, the output i obtained is: false. Whereas
[quoted text clipped - 11 lines]
>    StringBuffers use identity to determine equality, not contents.
> Strings use contents to determine equality.

Yes, but why was that decision made?
Chris Smith - 01 Sep 2006 16:06 GMT
> Yes, but why was that decision made?

There are two approaches to the use of equals(Object).  Unfortunately,
both are used from within the Java standard API.

The first approach says that equals(Object) should represent the concept
of two objects being the same. If a.equals(b) then it doesn't matter
whether I have a reference to 'a' or a reference to 'b'.  This allows
equals(Object) to be overridden for String, Integer, Double, and any
other immutable value type.  This approach would forbid implementing
equals(Object) to do comparison of contents for StringBuffer, because
even if two StringBuffer objects currently contain the same thing, I can
call append on one of them and it will be different from the other.  Put
another way, it does matter whether I've got a reference to 'a' or 'b',
because someone might be modifying 'a'.

The second approach is that equals(Object) should be overridden to
implement whatever concept of equality seems most useful to the person
specifying a class or interface.  In the standard API, this is seen for
java.util.List, which says that two lists are equal if they have the
same contents.  This clearly violates the rule of the earlier approach,
since I can add elements to some Lists.  The Collections API designer
just had a different idea about the proper use of equals(Object).

The first approach works better.  For example, it is *not* safe to use
objects that have chosen this second approach as keys in a HashMap or
Hashtable.  However, the second approach meshes better with some
people's intuition about what "equals" means, and it avoids the needs to
add other methods to do something like compare two Lists to see if they
have the same contents.

Signature

Chris Smith

Chris Uppal - 01 Sep 2006 16:27 GMT
> There are two approaches to the use of equals(Object).  Unfortunately,
> both are used from within the Java standard API.
[quoted text clipped - 6 lines]
> implement whatever concept of equality seems most useful to the person
> specifying a class or interface.

Incidentally, I think the two approaches converge in this case.  The name of
the class is StringBuffer (and later StringBuilder), not something like
MutableString.  Instances have jobs to do, and that job is not representing
textual data, but knowing how to /assemble/ a String.

As such they are worker objects, and even when following the second approach
the "convenient equality" would tend to say that two instances were equal if
they were identically configured and were applying themselves to the same
target object.   I can imagine builder objects for which those criteria would
allow a notion of equality that was weaker than identity, but I don't think
that's possible for StringBuilder.

(As an aside, I think the choice of toString() as the method to extract the
assembled String from the Builder was somewhat unfortunate since that isn't at
all what toString() /means/.)

   -- chris


Free Magazines

Get these publications absolutely FREE for up to 12 months. There are no hidden fees and no obligation. Simply choose a title, complete the application form and submit it. Read more ...

Oracle MagazineNetwork ComputingComputer WorldBio-IT WorldeWeekInformation WeekInfosecurity
 
Sign In
Join
My Latest Posts
My Monitored Threads
My Blog
My Photo Gallery
My Profile
My Homepage

Start New Thread
Enable EMail Alerts
Rate this Thread



©2008 Advenet LLC   Privacy Policy - Terms of Use
This website includes both content owned or controlled by Advenet as well as content owned or controlled by third parties.