Is StringBuilder equal in C# and Java?

HathimW

Mitglied
I recently discovered this StringBuilder.

Where java StringBuilder does not implement Equals(). However, I discovered an Equals() implementation for the StringBuilder class in C#. I'd want to know how this is handled in C# and why it isn't addressed in Java.

Source: Scaler
 

httpdigest

Top Contributor
Ja, ich glaube, sein Hauptargument war eher: "and its primary use is for constructing strings".
java.util.List ist ein Interface und überschreibt equals() nicht.
Und seine möglichen Implementierungen wie ArrayList oder eine LinkedList sind ja nicht dazu da, ein "Array" zu konstruieren.
 

vish234

Mitglied
Well Although StringBuilder.equals() exists, it does not compare the Strings. This is the proper way from a Java standpoint. StringBuilders change by definition, which renders two separate StringBuilder instances un-equal. Although there are exceptions, most recent Java APIs follow the concept that equal() is provided for immutable or final classes. Mutable classes, on the other hand, often inherit Object.equals(), which is object-identity-based.
This is due to at least two factors. One is the ability to utilise objects appropriately in hash-based data structures, such as as a value in a HashSet or a key in a HashMap. Although this is dependent on Object.hashCode(), it has an impact on Object.equals() since hashCode should be stable during the life of an object if it is to be used as an entry in a hash-based datastructure, and equals() is specified to be consistent with hashCode ().

The other issue is that Object.equals() is supposed to be symmetrical, and carelessly modifying it might destroy that symmetry.

Overall, in Java, Object.equals() should be interpreted as equality based on the nature of the instances rather than value equality.

Hope this help for anyone new here on this post.
 

Ähnliche Java Themen

Neue Themen


Oben