Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why override equals instead of using another method name

Tags:

java

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?

like image 726
Lakshitha Ranasinghe Avatar asked Jan 21 '15 10:01

Lakshitha Ranasinghe


People also ask

What is the reason for overriding equals () method?

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?

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.

What happens if you only override equals method?

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.

What happens if you override equals but not hashCode?

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 ...


1 Answers

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.

like image 164
aioobe Avatar answered Sep 28 '22 17:09

aioobe