简体   繁体   English

StringBuilder在C#和Java中相等

[英]StringBuilder Equals in c# and Java

I have just come across this StringBuilder .equals Java , where java StringBuilder does not have Equals() implementation. 我刚刚遇到过这个StringBuilder .equals Java ,其中Java StringBuilder没有Equals()实现。 However, in c# I observed there is an Equals() implementation available for StringBuilder class. 但是,在c#中,我观察到StringBuilder类有一个Equals()实现。 I would particularly want to know how this is handled in C# and why not in Java. 我特别想知道如何在C#中处理它,以及为什么不在Java中处理。

StringBuilder.equals() actually exists, but it does not compare the Strings. StringBuilder.equals()实际上存在,但是不比较字符串。 From a Java perspective, this is the correct approach. 从Java的角度来看,这是正确的方法。 StringBuilder s mutate, that's their purpose, which makes two different StringBuilder objects un-equal by definition. StringBuilder的变异,这是根据目的使两个不同的StringBuilder对象不相等。 Most newer Java APIs follow the approach that equal() is implemented for immutable or final classes, although there are exceptions. 大多数更新的Java API都遵循为不可变或最终类实现equal()的方法,尽管有例外。 Mutable classes, on the other hand, usually simply inherit Object.equals() which relies on object-identity. 另一方面,可变类通常仅继承Object.equals() ,而Object.equals()依赖于对象身份。

There are at least two reasons behind this. 这背后至少有两个原因。 One is the ability to properly use objects in hash-based data structures, ie as value in a HashSet or a key in a HashMap . 一种是在基于哈希的数据结构中正确使用对象的能力,即作为HashSet值或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() . 尽管这取决于Object.hashCode() ,但它会影响Object.equals()因为如果将hashCode用作基于哈希的数据结构中的条目,则该hashCode在对象的生存期内应该是稳定的,并且equals()被定义与hashCode()一致。

The other is that Object.equals() is defined to be symmetrical, and carelessly overriding Object.equals() can break that symmetry. 另一个是Object.equals()被定义为对称的,并且不小心覆盖Object.equals()可能会破坏该对称性。

All in all, in Java, Object.equals() shouldn't be understood as value-equality but as equality according to the nature of the instances. 总而言之,在Java中, Object.equals()不应理解为值相等,而应根据实例的性质理解为相等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM