I don't understand why StringBuilder's .equals method is the same as the ineffectual == operator; why didn't they make it actually evaluate the objects rather than forcing us to write an override?
First of all, the == operator is NOT ineffectual; it does exactly what it should do - it determines whether two variables reference the same StringBuilder.
Second, you don't have to create an override to compare the string content of two StringBuilders:
As SB stands now, I have to write my own equals method or use .toString() to do what is common: compare strings, which seems to go against the "code re-use" philosophy. Or am I missing something? (which I'm defaulting to the latter...so what am I missing?)
I meant ineffectual at comparing two strings, which is would I would assume would be more predominantly done with Strings and StringBuilder objects. I can understand keeping == consistent across all object references but what I do not understand is that we can use .equals with String but not with the 'improved' StringBuilder--what was the design behind that decision that I am missing?
That merits a thread of its own, so I might separate this post into a new thread. Original question was here.
Julian West wrote:. . . why StringBuilder's .equals method is the same as the ineffectual == operator . . .
There is nothing ineffectual about ==; when applied to reference types it tells you whether what is on its left and what is on its right is the same object. Most of the time that returns false, so you use the equals() method instead. The use of == on reference types should be avoided except for a few exceptions. The exceptions include:-
If you need to find out whether two StringBuilders have the same contents use
It's job is to build up a String that you will use later on, so comparison doesn't make much sense.
If you find yourself doing sb.toString().equals(anotherSB.toString()) then it's quite likely you are doing something a little wrong. Not always, as I expect someone has a use for it, but I have never seen one.
For instance, a List is a data type. You can use the equals() method to compare the two lists for their content.
A StringBuilder is a 'do type'. Even if the contents of two instances may be the same, they may be used in different ways to create two different end results. One could argue the same is true for a List, but lists represent data now. Builders represent data in the future.