I would like to know whether StringBuffer can be used to compare string. I complied and run the foll codes and it shows nothing.
Originally posted by Frank Carver:
The two StringBuffers don't come out as equal, because StringBuffer just uses the "default" implementation of equals(), which does the same as '==' and directly compares the object references. The two StringBuffers are different objects with different references, so they come out as non-equal.
Originally posted by Hari Gangadharan:
I really love this question! The StringBuffer *does* not override Object's "equals" method whereas String do. Hence when you invoke s1.equals(s2), the equals method of Object is invoked. The equals method of Object just does a shallow compare (which essentially is s1 == s2) and returns false!
Hope this helps --
[This message has been edited by Johannes de Jong (edited April 06, 2001).]
sb1 and sb2 are entirely seperate instances of a StringBuffer object complete with their own references and that is why they aren't equal, because the references are different?
If so, how could they ever be equal? I assume only by assigning ones value to the other like "sb1 = sb2". What happens when this is done, is the sb2 OBJECT actually deleted (or ready for GC?) so that you now have two references to the sb1 OBJECT?
If so, what happens if I change sb1, is sb2 also changed? If this is true, what is the value in having multiple references to the same OBJECT?
Back to the original question, how should this comparison be handled, something like this? (code is psuedo-code: the method names might be wrong)
Sorry if this is too many questions at once but I thought they were all related. I feel on the verge of understanding this, which would be a big boost...
[This message has been edited by Joel Cochran (edited April 06, 2001).]
The only way for two object references to be equal is if they both refer to the same object.
You are right that when you set one reference equal to another, then if there are no *other* references to the object it is eligible for garbage collection. But check your logic on this:
if you say "sb1=sb2", then which object is eligible for GC? It's "the object formerly refered to by sb1". not sb2, like you mentioned.
[This message has been edited by Mike Curwen (edited April 06, 2001).]