Darey
Darey

Reputation: 497

StringBuilder Equals in c# and Java

I have just come across this StringBuilder .equals Java, where java StringBuilder does not have Equals() implementation. However, in c# I observed there is an Equals() implementation available for StringBuilder class. I would particularly want to know how this is handled in C# and why not in Java.

Upvotes: 0

Views: 105

Answers (1)

Christian Hujer
Christian Hujer

Reputation: 17965

StringBuilder.equals() actually exists, but it does not compare the Strings. From a Java perspective, this is the correct approach. StringBuilders mutate, that's their purpose, which makes two different StringBuilder objects un-equal by definition. Most newer Java APIs follow the approach that equal() is implemented for immutable or final classes, although there are exceptions. Mutable classes, on the other hand, usually simply inherit Object.equals() which relies on object-identity.

There are at least two reasons behind this. One is the ability to properly use objects in hash-based data structures, i.e. as value in a HashSet or a key in a HashMap. Although this depends on Object.hashCode(), it affects Object.equals() because the hashCode should be stable over an object's life time if it is to be used as an entry in a hash-based datastructure, and equals() is defined to be consistent with hashCode().

The other is that Object.equals() is defined to be symmetrical, and carelessly overriding Object.equals() can break that symmetry.

All in all, in Java, Object.equals() shouldn't be understood as value-equality but as equality according to the nature of the instances.

Upvotes: 2

Related Questions