Guillermo Ishi wrote:
Roel De Nijs wrote:
Guillermo Ishi wrote:s1.equals(s2) is false is unfathomable...
It's not at all! StringBuilder doesn't override the equals() method of class Object. So the equals() method will only return true if s1 and s2 refer to the same StringBuilder instance.
Is there a method behind that madness?
Sure! That's why it's not madness but common sense
A
StringBuilder's main and only purpose is to build strings (without creating a new
String on every operation), hence it's name
So it's kind of a helper class, and you only will use it to do a bunch of string manipulations (append, replace, insert, remove,...) to end up with an actual String (by invoking the
toString() method). So the
Java API developers decided not to implement/override the
equals() method, because nobody will ever be interested to know if two
StringBuilders are meaningfully equal. Everybody will use them to create strings, not to compare them.
If I look at my own codebase of our application, only a very tiny percentage of our classes override the
equals() (and
hashCode()) method(s) for exactly the same reason. For example: a repository is used to access the database and perform some CRUD (create, read, update and delete) operations, not to compare if this repository is meaningfully equal to another one.
Hope it helps!
Kind regards,
Roel