Why do we need to override equals() and hascode() method of object class?

Answer Posted / javamasque

As per equality contract of Java if two objects are equal then they should return equal integer, means if obj1.equals(obj2) then obj1.hashCode() == obj2.hashCode();

As we override equals method we compares equality on value of each property inside 1st object with 2nd object, as it finds all properties are equal then returns true else false.

As we override hascode method we generate a unique integer by multiplying with prime number. If we multiply with prime number then there is most possibility to get unique integer. The prime number 31 is mostly used as the hascode method is override.

Is This Answer Correct ?    2 Yes 0 No



Post New Answer       View All Answers


Please Help Members By Posting Answers For Below Questions

What are the different access modifiers available in java?

809


How do you override a method in java?

765


Differentiate between a class and an object.

813


What are the drawbacks of singleton class?

798


What is finally block?

769


What is Enum in Java?

919


What is immutable class in java?

717


Can a java program have 2 main methods?

803


Explain the polymorphism principle?

798


Can you have two constructors in java?

709


Why string is called as immutable?

731


What are 5 boolean operators?

849


What is the requirement of thread in java?

840


What are static blocks and static initalizers in java ?

792


Can we extend private class in java?

786