Possible Duplicate:
Why ReferenceEquals and == operator behave different from Equals
The default implementation of ==
operator compares objects by references. So when you override Equals (which default behaviour is the same) you have to also specify ==
and !=
operators so that they call Equals (and make it in every class of hierarchy as ==
and !=
operators are not virtual).
My question is why it is so? Why does ==
and !=
compare objects by reference instead of using Equals? I guess there should be a reason for such a fundamental thing.
Update.
To comments: I assumed ==
should depend on Equals (but not vice versa) as you can override Equals in base class and use this implementation in derived classes automatically. It wouldn't work if Equals used ==
in its implementation, as ==
is not virtual.
Uses of hashCode() and equals() Methods Its default implementation simply checks the object references of two objects to verify their equality. By default, two objects are equal if and only if they are refer to the same memory location. Most Java classes override this method to provide their own comparison logic.
A HashMap is not allowed to have multiple equal keys! Not after we have overridden the equals() method on Person Class. That is the reason why we must override hashCode() method after we have overridden equals method.
The equals() and hashcode() are the two important methods provided by the Object class for comparing objects. Since the Object class is the parent class for all Java objects, hence all objects inherit the default implementation of these two methods.
String class, hashCode() method is also overrided so that two equal string objects according to equals() method will return same hash code values. That means, if s1 and s2 are two equal string objects according to equals() method, then invoking s1. hashCode() == s2.
I believe the main reason is ==
is a static operator and can be called on null
objects while Equals
requires an instance.
For example:
Foo foo1 = null; Foo foo2 = null; Console.WriteLine(foo1 == foo2); // cannot use Equals
Object.ReferenceEquals is a static
member that compares reference equality. Even value types are boxed before being passed to that method.
What about Equals
, it's a virtual
method, which means it lets to a consumer to override a functionality.
So default implementation of ==
behavior presumes default comparison(reference) is ok for you, if you need something specific, in this case framework provides you with a virtual
method, which can be overriden.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With