d2jsp
Log InRegister
d2jsp Forums > Off-Topic > Computers & IT > Programming & Development > Hashcode & Equals Method
Add Reply New Topic New Poll
Member
Posts: 31,354
Joined: Mar 25 2009
Gold: 15.00
Feb 15 2023 01:45pm
What situations do you need to use them both, and with what collections?
Member
Posts: 4,850
Joined: Mar 1 2008
Gold: 5,064.33
Feb 20 2023 10:06am
you have to override both if you need either of them
if you want a particular class to be check for equality on their properties, then it makes sense to override it
usually when the class is an entity it's better to leave the default implementation
Member
Posts: 31,354
Joined: Mar 25 2009
Gold: 15.00
Feb 20 2023 12:05pm
Quote (diobrando89 @ Feb 20 2023 11:06am)
you have to override both if you need either of them
if you want a particular class to be check for equality on their properties, then it makes sense to override it
usually when the class is an entity it's better to leave the default implementation


ty!
Member
Posts: 44,551
Joined: Nov 18 2007
Gold: 306,382.55
Mar 7 2023 10:37am
The hashCode() and equals() methods are used to compare objects in Java.

The hashCode() method returns an integer value that represents the hash code of an object. This value is used by certain collections, such as HashSet and HashMap, to quickly identify if two objects are likely to be equal.

The equals() method is used to compare the actual contents of two objects to determine if they are equal.

In most cases, if you override the equals() method, you should also override the hashCode() method. This is because if two objects are equal according to the equals() method, they should also have the same hash code.

Therefore, you would typically use both methods when working with collections that rely on hash codes for efficiency, such as HashSet, HashMap, Hashtable, and IdentityHashMap.

Additionally, you might also use both methods when implementing your own classes that need to be compared for equality, especially if you plan on using them in collections that rely on hash codes.
Go Back To Programming & Development Topic List
Add Reply New Topic New Poll