Forums Register Login

String / StringBuffer and equals

+Pie Number of slices to send: Send
Hi,
consider the following code:
String s = new String("abc");
StringBuffer sb = new StringBuffer("abc");
The expression sb.equals(s) is false, but why is s.equals(sb) false?
I know that StringBuffer does not override equals, but String does. So I expected that s.equals(sb) calls the overloaded String method which goes after the contents of sb, not the reference address itself.
Any ideas?
Thanks,
Bernd
+Pie Number of slices to send: Send
Hi,
Equals on StringBuffer does a shallow comparison. (same like ==) Will return true only if the objects are same.

Clement
+Pie Number of slices to send: Send
Yep. I always tell myself when I see a StringBuffer and I want to compare a String to it's contents, I have to use toString() on the StringBuffer first.
+Pie Number of slices to send: Send
The equals method takes an Object as a paramater (because it's defined in the Object class), but, in general, if you call equals on one object type and pass it another object type, it'll always come back as false.
It just doesn't make sense for two entirely different types of objects to be "equal." However, had you done this:

Now you'd be comparing a String object with a String object, which makes more sense than comparing a String object with a StringBuffer object.
I hope that helps,
Corey
+Pie Number of slices to send: Send
 

Originally posted by Corey McGlone:

It just doesn't make sense for two entirely different types of objects to be "equal." However, had you done this:


Maybe another way to think about it, if it helps to resolve the confusion, is this:
Sun had something in particular in mind when they created the 'equals' method. There is a moral contract it is expected to obey. That contract is "only return true if the implementation of the two objects is equivalent".
That isn't the same as "only return true if the two objects could be thought of has having equivalent values for some particular purpose".
The Sun notion of equals is more stringent, and really better from an OO programming standpoint. It allows you to have a reasonable expectation that you could use X and Y interchangeably in a wide variety of situations, although there are some limitations to that.
+Pie Number of slices to send: Send
Hello All,
thanks for your feedback, this is very helpful for me.
-Bernd
+Pie Number of slices to send: Send
Rule of thumb:
(StringBuffer).equals(String) OR
String.equals(StringBuffer)
both always return false
It means our mission is in jeapordy! Quick, read this tiny ad!
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 663 times.
Similar Threads
String.equals() ....confusing
a simple quiz on string equals
EQUALS method
equals
equals() in Wrapper Classes
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 23:06:56.