How equals method works in StringBuffer?

S

swornavidhya_m

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
 
C

Chris Smith

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.
 
J

Jeffrey Schwab

Chris said:
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())
 
P

Patricia Shanahan

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

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
 
O

Oliver Wong

Jeffrey Schwab said:
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
 
J

Jeffrey Schwab

Oliver said:
StringBuffers use identity to determine equality, not contents.
Strings use contents to determine equality.

Yes, but why was that decision made?
 
C

Chris Smith

Jeffrey Schwab said:
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.
 
C

Chris Uppal

Chris said:
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'.

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.

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
 
Joined
Dec 27, 2010
Messages
1
Reaction score
0
Wath out for NullPointerException's!

Code:
StringBuffer sb1 = null;
StringBuffer sb2 = null;
boolean equals = String.valueOf(sb1).equals(String.valueOf(sb2));
System.out.println(equals);

Although it would be better to create your own Util method with something like:

Code:
public class EqualsUtil {
    public static boolean equals(StringBuffer sb1, StringBuffer sb2) {
        boolean equal = false;

        if(sb1 == null && sb2 == null) {
            equal = true;
        } else if(sb1 != null && sb2 != null) {
            equal = sb1.toString().equals(sb2.toString());
        }

        return equal;
    }
}
 
Joined
Dec 24, 2010
Messages
19
Reaction score
0
DJDaveMark said:
Wath out for NullPointerException's!

Code:
StringBuffer sb1 = null;
StringBuffer sb2 = null;
boolean equals = String.valueOf(sb1).equals(String.valueOf(sb2));
System.out.println(equals);

Although it would be better to create your own Util method with something like:

Code:
public class EqualsUtil {
    public static boolean equals(StringBuffer sb1, StringBuffer sb2) {
        boolean equal = false;

        if(sb1 == null && sb2 == null) {
            equal = true;
        } else if(sb1 != null && sb2 != null) {
            equal = sb1.toString().equals(sb2.toString());
        }

        return equal;
    }
}


good advice DJDaveMark ...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,537
Members
45,022
Latest member
MaybelleMa

Latest Threads

Top