This seems like a silly question but why do we override equals
method instead of creating a new method with new name and compare using it?
If I didn't override equals that means both ==
and equals check whether both references are pointed to same memory location?
We can override the equals method in our class to check whether two objects have same data or not.
Why does it generally make more sense to override the equals method than to overload it? If equals is overridden, then you end up with two equals methods for the same class. Which one gets called will depend on the argument type. This usually isn't the intended behavior.
If we only override equals(Object) method, when we call map. put(g1, “CSE”); it will hash to some bucket location and when we call map. put(g2, “IT”); it will hash to some other bucket location because of different hashcode value as hashCode() method has not been overridden.
Overriding only equals() method without overriding hashCode() causes the two equal instances to have unequal hash codes, which violates the hashCode contract (mentioned in Javadoc) that clearly says, if two objects are equal according to the equals(Object) method, then calling the hashCode method on each of the two ...
This seems like a silly question but why do we override
equals
method instead of creating a new method with new name and compare using it?
Because all standard collections (ArrayList
, LinkedList
, HashSet
, HashMap
, ...) use equals
when deciding if two objects are equal.
If you invent a new method these collections wouldn't know about it and not work as intended.
The following is very important to understand: If a collection such as ArrayList
calls Object.equals
this call will, in runtime, resolve to the overridden method. So even though you invent classes that the collections are not aware of, they can still invoke methods, such as equals
, on those classes.
If I didn't override equals that means both
==
and equals check whether both references are pointed to same memory location?
Yes. The implementation of Object.equals
just performs a ==
check.
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