Why I must implement hashCode() when overriding equals ()? | Sololearn: Learn to code for FREE!
¡Nuevo curso! ¡Todo programador debería aprender IA Generativa!
Prueba una lección gratuita
0

Why I must implement hashCode() when overriding equals ()?

10th Mar 2016, 3:09 PM
ūüáßūüá∑ Caio Amaral
ūüáßūüá∑ Caio Amaral - avatar
4 Respuestas
+ 4
Here is some explanation: "In Java, every object has access to the equals() method because it is inherited from the Object class. However, this default implementation just simply compares the memory addresses of the objects. You can override the default implementation of the equals() method defined in java.lang.Object. If you override the equals(), you MUST also override hashCode(). Otherwise a violation of the general contract for Object.hashCode will occur, which can have unexpected repercussions when your class is in conjunction with all hash-based collections." Source: http://www.xyzws.com/javafaq/why-always-override-hashcode-if-overriding-equals/20
18th May 2016, 4:42 PM
James Flanders
+ 1
Harshit Agarwal Harsh Dugar Aayush Tamang Koushal Lahoti Ritesh Sha Akash Joshi Ana Paul Mansi Priya Mahek Mantri Priyanka Roy Drimi Ben's Chisim Sangma Priyanka Roy Rishav Goenka B'dan Marak Harshit Jain Sakir Akhter SNeha Bagrodia
17th Oct 2016, 2:54 AM
Sam
0
equals method is presented in object class and it's meant for reference comparison. String class has overridden Object class equals method which is meant for reference comparison to Content comparison. So depending upon your requirement if you need content comparison you can over ride Object class equals method.
16th Sep 2016, 1:54 PM
Sarath chalapaka
Sarath chalapaka - avatar
0
hashCode() is present in Object class it's the unique number which will be generated by JVM to identify each object uniquely.
16th Sep 2016, 1:56 PM
Sarath chalapaka
Sarath chalapaka - avatar