Avatar of sudhakar_koundinya
sudhakar_koundinya

asked on 

Overriding equals method

Hello All,

While overriding equals method, is it must to write the hashCode method also?? Or is it just optional??

Thanks
Sudhakar
Java

Avatar of undefined
Last Comment
baboo_
ASKER CERTIFIED SOLUTION
Avatar of CodingExperts
CodingExperts

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of baboo_
baboo_

If you're planning on using your objects in a Hashtable data structure, you should override the hashCode() method.

The reason is that a Hashtable implemented in Java uses a combination of the equals() AND hashCode() methods to do its searching and storing of data.

It depends on what your doing, really.  If this is a class that only YOU will be using, and you know that you won't be using a Hashtable to store your data, then you could get away without overriding hashCode.  But if you're writing a  class to be used in a programming library, then you should override hashCode so others using your class won't have problems.

baboo_
Java
Java

Java is a platform-independent, object-oriented programming language and run-time environment, designed to have as few implementation dependencies as possible such that developers can write one set of code across all platforms using libraries. Most devices will not run Java natively, and require a run-time component to be installed in order to execute a Java program.

102K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo