Equals and Hashcode Contract in Java [Important Java Interview Question] | Code Decode

  Рет қаралды 156,223

Code Decode

Code Decode

4 жыл бұрын

In this video of code decode we have covered Equals and hashcode contract || Equals and hashcode in Java
Udemy Course of Code Decode on Microservice k8s AWS CICD link:
openinapp.co/udemycourse
Course Description Video :
yt.openinapp.co/dmjvd
In this video equals and hashcode contract By default, the Java super class java.lang.Object provides two important methods for comparing objects: equals() and hashcode(). These methods become very useful when implementing interactions between several classes in large projects. In this article, we will talk about the relationship between these methods, their default implementations, and the circumstances that force developers to provide a custom implementation for each of them.
equals(Object obj): a method provided by java.lang.Object that indicates whether some other object passed as an argument is "equal to" the current instance. The default implementation provided by the JDK is based on memory location - two objects are equal if and only if they are stored in the same memory address.
hashcode(): a method provided by java.lang.Object that returns an integer representation of the object memory address. By default, this method returns a random integer that is unique for each instance. This integer might change between several executions of the application and won't stay the same
How equals and hashcode contract works in java ?
The default implementation is not enough to satisfy business needs, especially if we're talking about a huge application that considers two objects as equal when some business fact happens. In some business scenarios, developers provide their own implementation in order to force their own equality mechanism regardless the memory addresses.
As per the Java documentation in perspective of equal and hashcode contract, developers should override both methods in order to achieve a fully working equality mechanism - it's not enough to just implement the equals() method.
equals and hashcode in java,equals and hashcode in java by durga,equals and hashcode contract in java,equals and hashcode contract,equals and hashcode in java telusko,equals and hashcode method in java,java equals and hashcode,java equals and hashcode contract,what is equals and hashcode contract,what is equals and hashcode in java,how equals and hashcode works in java,equals and hashcode implementation,hashcode and equals method in java,java,equals and hashcode contract example,contract between equals and hashcode in java
-------------------------------------------------------------------------------------------------------------------------------------
Code Decode Playlists
Most Asked Core Java Interview Questions and Answers : • Core Java frequently a...
Advance Java Interview Questions and Answers : • Advance Java Interview...
Java 8 Interview Questions and Answers : • Java 8 Interview Quest...
Hibernate Interview Questions and Answers : • Hibernate Interview Qu...
Spring Boot Interview Questions and Answers : • Advance Java Interview...
Angular Playlist : • Angular Course Introdu...
GIT : • GIT
-------------------------------------------------------------------------------------------------------------------------------------
Subscriber and Follow Code Decode
Subscriber Code Decode : kzfaq.info?...
Linkedin : / codedecodeyoutube
Instagram : / codedecode25
--------------------------------------------------------------------------------------------------------------------------------------
#equalsandhashcode #equalsandhashcodecontract #java

Пікірлер: 129
@jiniamitra7593
@jiniamitra7593 3 жыл бұрын
Main point is equals method will get called when for key hashcode value is same.
@ragakaplish501
@ragakaplish501 2 жыл бұрын
most easy and we explained video very very thanks a lot most helpful video cleared my all doubts keep up the good work .
@CodeDecode
@CodeDecode 2 жыл бұрын
Thanks a lot Raga 🙂👍
@sudarshankalvankar1827
@sudarshankalvankar1827 Жыл бұрын
Thanks for supporting us .Video is really useful to understand the concept.
@CodeDecode
@CodeDecode Жыл бұрын
you're welcome
@menaceasif
@menaceasif 3 жыл бұрын
Thanks for ur explanation ma'am.... Really helped me to understand it better...
@CodeDecode
@CodeDecode 3 жыл бұрын
M glad it helps 🙃
@yoshitamahajan353
@yoshitamahajan353 3 жыл бұрын
Thanks this is best explanation over the net..
@CodeDecode
@CodeDecode 3 жыл бұрын
M glad you find it helpful
@aditis4993
@aditis4993 2 жыл бұрын
I can't tell you enough how awesome you are for making these videos. Thank you
@CodeDecode
@CodeDecode 2 жыл бұрын
Thanks Aditi 🙂🙂👍👍
@EasyTechStudios
@EasyTechStudios 4 жыл бұрын
Thanks 🙌🙌
@vinieas2373
@vinieas2373 3 жыл бұрын
Surely Aasaam Your explanation and all the topics all very cleared mam
@CodeDecode
@CodeDecode 3 жыл бұрын
Thanks vini 👍👍
@rajajodhani8024
@rajajodhani8024 2 жыл бұрын
You are really awesome in explaining things, i seen some other videos of you as well for other topics, really fell in love with your videos Thankyou
@CodeDecode
@CodeDecode 2 жыл бұрын
Thanks Raja🙂👍
@srijanbiswas
@srijanbiswas 2 жыл бұрын
shouldnt we add @Override annotation for overridng hashcode() ??
@amitsh5413
@amitsh5413 2 жыл бұрын
Is there any video related to internal implementation of hash code on your channel
@soumyaranjan6196
@soumyaranjan6196 3 жыл бұрын
your explanation is very clear.Please make a video on internals of hashmap
@CodeDecode
@CodeDecode 3 жыл бұрын
Sure will upload that soon
@naveenkumarmaddala7830
@naveenkumarmaddala7830 4 жыл бұрын
Hi, Thanks for sharing the video. In your example can you explain hashcode scenario. Like equals can you take one example on hashcode and explain it. Thanks Naveen.
@CodeDecode
@CodeDecode 4 жыл бұрын
Sure. I will cover hash code and it's working in detail very soon.
@harshinredzone
@harshinredzone Жыл бұрын
Helpful video. Thank you ma'am.
@CodeDecode
@CodeDecode Жыл бұрын
you're welcome
@jonuranu8151
@jonuranu8151 3 жыл бұрын
if you do e2.setid(2) then also it will give true is this correct? because you have provided condition e=o then return true.
@satishhawalppagol1892
@satishhawalppagol1892 3 жыл бұрын
I have some few questions on equals and hashcode _ Advance-Thanks :) _ - Suppose I have Student and Address class. Address class is field in Student(has a relationship). If I create two objects of class Student(deep copy - Address is also created) Is hashcode() return same / equals() return true- 1.What If I don't override equals() and hashcode() in any of class whether the two object are equal. 2.What If I override equals() and Not hashcode() in Student and nothing overridden in Address. 3.What If I only override hashcode() in Student and nothing overridden in Address. 4.What If I override equals() and Not hashcode() in Address and nothing overridden in Student. 5.What If I only override hashcode() in Address and nothing overridden in Student. 6.what if I return always true from equals() and no hashcode overridden in student and nothing overridden in Address 7.what if I return always same value from hashcode() and no equals overridden in student and nothing overridden in Address 8.what if I return always true from equals() and no hashcode overridden in Address and nothing overridden in Student 9.what if I return always same value from hashcode() and no equals overridden in Address and nothing overridden in Student.
@aishurajas2507
@aishurajas2507 3 жыл бұрын
Mostly asked questions in Interview..👍
@dystopianNinja1289
@dystopianNinja1289 3 жыл бұрын
please let me know the answer once you have got the answers. Thank you :)
@vijaynarayanan2836
@vijaynarayanan2836 8 ай бұрын
In Java, the `equals()` and `hashCode()` methods are used for object comparison and to determine the hash value of objects, respectively. The behavior of these methods plays a crucial role in various operations, including storing objects in collections like HashMap, HashSet, etc. Let's go through your scenarios one by one: 1. If neither `equals()` nor `hashCode()` is overridden: - The default implementations from the `Object` class will be used. - `equals()` will perform reference equality (`==`), and two different objects will not be considered equal, even if their contents are the same. - `hashCode()` will return different hash codes for different objects, even if their contents are the same. 2. If only `equals()` is overridden in Student: - `equals()` will use the overridden implementation for Student comparisons. - `hashCode()` will still use the default implementation from the Object class. - As a result, the hash codes will be different for equal Student objects, causing issues in collections like HashMap. 3. If only `hashCode()` is overridden in Student: - `hashCode()` will use the overridden implementation, but `equals()` will use the default implementation. - This can lead to inconsistent behavior when comparing objects for equality. 4. If only `equals()` is overridden in Address: - `equals()` will use the overridden implementation for Address comparisons. - `hashCode()` will still use the default implementation from the Object class. - Similar to scenario 2, hash codes will be different for equal Address objects. 5. If only `hashCode()` is overridden in Address: - `hashCode()` will use the overridden implementation, but `equals()` will use the default implementation. - This can lead to inconsistent behavior when comparing objects for equality. 6. If `equals()` always returns true in Student: - All Student objects will be considered equal, but hash codes will likely be different (using the default `hashCode()` implementation). - This will lead to issues when trying to use Student objects in hash-based collections like HashMap or HashSet. 7. If `hashCode()` always returns the same value in Student: - All Student objects will have the same hash code, regardless of their actual content. - `equals()` will still use the default implementation. - This can cause performance issues in hash-based collections, as objects will all map to the same bucket. 8. If `equals()` always returns true in Address: - All Address objects will be considered equal, but hash codes will likely be different (using the default `hashCode()` implementation). - This will lead to issues when trying to use Address objects in hash-based collections. 9. If `hashCode()` always returns the same value in Address: - All Address objects will have the same hash code, regardless of their actual content. - `equals()` will still use the default implementation. - Similar to scenario 7, this can cause performance issues in hash-based collections. To ensure consistent and correct behavior, it's recommended to override both `equals()` and `hashCode()` whenever you override one of them. Additionally, their implementations should be consistent with each other, following the contract specified in the Java documentation.
@krishnanitturkar2793
@krishnanitturkar2793 11 ай бұрын
Amazing explaination mam, Thanks.
@CodeDecode
@CodeDecode 11 ай бұрын
🙂🙂Thanks 👍👍
@manasdeora4601
@manasdeora4601 3 жыл бұрын
Very properly explained.
@CodeDecode
@CodeDecode 3 жыл бұрын
Thanks Manas 👍👍
@manishchavan1760
@manishchavan1760 2 жыл бұрын
Thanks for explain.
@CodeDecode
@CodeDecode 2 жыл бұрын
You're welcome manish
@subhadipde7636
@subhadipde7636 2 жыл бұрын
Awesome explanation ..
@CodeDecode
@CodeDecode 2 жыл бұрын
Thanks
@rahuldebnath3919
@rahuldebnath3919 Жыл бұрын
I have a question on hashcode , as you are saying in this video that "hash code is a integer value which defines at which memory location does this particular object is going to store in HashTable" . As we know objects are stored in Heap memory, so does that mean heap memory is constructed using HashTable to store/manage objects ?
@roopkishore785
@roopkishore785 Жыл бұрын
1 .) HashCode is the integer value calculated with the help of memory address; 2.) In the hash table, we use hash code value to calculate the index of the Key being inserted into it.
@shankarpatilsp
@shankarpatilsp 3 жыл бұрын
Thanks!!
@CodeDecode
@CodeDecode 3 жыл бұрын
👍
@SumanthReddyAdudoodla
@SumanthReddyAdudoodla 5 ай бұрын
respect !!!
@CodeDecode
@CodeDecode 5 ай бұрын
Thanks
@manoharsitaram3300
@manoharsitaram3300 3 жыл бұрын
Nice. Can u make the video on immutable class and spring framework.
@CodeDecode
@CodeDecode 3 жыл бұрын
That's a nice suggestion. Will make the video on that too soon
@mohitg1
@mohitg1 3 жыл бұрын
thanks for the video.. you're doing a great job. all the very best & keep it up.
@CodeDecode
@CodeDecode 3 жыл бұрын
Thanks.... :-)
@ANILKUMAR-cc3lb
@ANILKUMAR-cc3lb 2 жыл бұрын
What if I'd is alphanumeric we cannot return it directly in hashcode right?
@saritachoudhury461
@saritachoudhury461 2 ай бұрын
your video contents are really great and helpful. But just a suggestion can you please minimize the usage of "NOTHING BUT" while explaining.
@jasper5016
@jasper5016 2 жыл бұрын
This is a really good video. Thanks. Can you please cover some other core java topics like Collections or Generics?
@CodeDecode
@CodeDecode 2 жыл бұрын
We have covered most of them kzfaq.info/sun/PLyHJZXNdCXscoyL5XEZoHHZ86_6h3GWE1
@dystopianNinja1289
@dystopianNinja1289 3 жыл бұрын
When you typecasted the object that was passed into Employee type, did you assume that if the id is same the employee name will be same too? since you called it equal only based on the id
@CodeDecode
@CodeDecode 3 жыл бұрын
Yes
@pratheeban3650
@pratheeban3650 Жыл бұрын
@@CodeDecode how is it possible? Employee name can be anything with same id for different objects. Right?
@surajkumarpatel5889
@surajkumarpatel5889 11 ай бұрын
@CodeDecode , you need to deep compare based on all fields. not only id right?
@rohitkapade1130
@rohitkapade1130 Жыл бұрын
thank you so much
@CodeDecode
@CodeDecode Жыл бұрын
you're welcome rohit
@unemployedcse3514
@unemployedcse3514 7 ай бұрын
It was asked in my interview ❤
@CodeDecode
@CodeDecode 7 ай бұрын
😊
@AmitKumar-pw1ln
@AmitKumar-pw1ln 3 жыл бұрын
Thanks a lot !! This cleared my doubts
@CodeDecode
@CodeDecode 3 жыл бұрын
You are most welcome....
@reeltorealworld5660
@reeltorealworld5660 3 жыл бұрын
Mam u made d variable private in employee class..plz tell me how we will acess or sort dis value in another class...
@CodeDecode
@CodeDecode 3 жыл бұрын
Any private variable can be accessed in other class using objects and getter setter methods.
@amarthyaseshu683
@amarthyaseshu683 3 жыл бұрын
thanks for sharing, very helpful while writing tests
@CodeDecode
@CodeDecode 3 жыл бұрын
👍👍🙂🙂
@theprofessor252
@theprofessor252 Жыл бұрын
Legend
@CodeDecode
@CodeDecode Жыл бұрын
❤️
@076_mohammadbelalansari4
@076_mohammadbelalansari4 8 күн бұрын
Great mam
@CodeDecode
@CodeDecode 6 күн бұрын
Thanks
@Naanu_kartik
@Naanu_kartik Жыл бұрын
Thanks 🙏
@CodeDecode
@CodeDecode Жыл бұрын
you're welcome
@gauravkhare1836
@gauravkhare1836 Ай бұрын
best 👍
@CodeDecode
@CodeDecode Ай бұрын
Thanks
@ShinAkuma
@ShinAkuma 2 жыл бұрын
New drinking game: Take a shot every time she says "nothing but the". JK, nice tutorials.
@CodeDecode
@CodeDecode 2 жыл бұрын
Will try to reduce usage. Thanks for the suggestion 👍🙂
@silpavig6838
@silpavig6838 3 жыл бұрын
Mam can you please make video on hash map interview questions including custom hash map topic
@CodeDecode
@CodeDecode 3 жыл бұрын
Sure will upload this topic soon
@ANILKUMAR-cc3lb
@ANILKUMAR-cc3lb 2 жыл бұрын
Will shallow comparison gives false still?
@braveKonoko
@braveKonoko 2 ай бұрын
What is the point of multiplying 31 with 1 and then adding it to the int value of id? You can simply add 31 to the id and return. 31 X 1 is 31 only right.
@Naveenraj093
@Naveenraj093 3 жыл бұрын
Hi can you please do a video on how hash code works internally please do pratical implementation
@CodeDecode
@CodeDecode 3 жыл бұрын
Sure Naveen. Will do that👍
@rupeshkumarbhavsar6093
@rupeshkumarbhavsar6093 3 жыл бұрын
can we use instanceOf operator instead of get class name for comparison?
@unemployedcse3514
@unemployedcse3514 7 ай бұрын
Yes
@VivekPatel-ux6vi
@VivekPatel-ux6vi 4 жыл бұрын
In third step of equals method do we need to compare all the property of that class?
@CodeDecode
@CodeDecode 4 жыл бұрын
No vivek. It depends on requirement. Suppose I want that if two employee objects have same I'd then I want them to be considered as equal even though they have different mobile numbers. That can be a case that one employee can have multiple phone numbers. So just comparing ids will be good. Hope I have answered your question.
@CodeDecode
@CodeDecode 4 жыл бұрын
If you still are not clear Lemme know I will eloborate more with real world examples.
@VivekPatel-ux6vi
@VivekPatel-ux6vi 4 жыл бұрын
@@CodeDecode thanks for your response, it's really helpful.
@gettoshubhi
@gettoshubhi 3 жыл бұрын
Please make video on multithreading in java and Strings
@CodeDecode
@CodeDecode 3 жыл бұрын
Sure 👍👍
@start1learn-n171
@start1learn-n171 2 ай бұрын
Tq
@CodeDecode
@CodeDecode 2 ай бұрын
Welcome
@yoshitamahajan353
@yoshitamahajan353 3 жыл бұрын
Hi can u please share internal implementation of trees, treemap...
@CodeDecode
@CodeDecode 3 жыл бұрын
Sure
@pecan8470
@pecan8470 2 жыл бұрын
saved my life
@CodeDecode
@CodeDecode 2 жыл бұрын
Glad to do that 😃👍👍
@pavanpavankalyan2790
@pavanpavankalyan2790 Жыл бұрын
How to write testcases for equals method
@josephfifstones
@josephfifstones Жыл бұрын
good content thanks :)
@CodeDecode
@CodeDecode Жыл бұрын
you're welcome yusuf
@ishansingh306
@ishansingh306 5 ай бұрын
Help me understand if(o == THIS){ return true; } i didn't understand it. this is a keyword how did you use it here?
@singhji4149
@singhji4149 10 ай бұрын
Hello Mam, After overriding equals and hashcode why e1==e2 is giving false?
@wasifkhan544
@wasifkhan544 8 ай бұрын
because of shallow compare, == compares the address of both the objects. Hence overriding equals method won't make them equal. Overriding equals helps in deep compare so e1.equals(e2) would be true.
@miraclepraveen2423
@miraclepraveen2423 Жыл бұрын
Maam you have implement equals() but didn't tell about hashcode() how to work
@seemadnimje1574
@seemadnimje1574 3 жыл бұрын
Hi, Your explanation is great, but the audio is too low. Thanks.
@CodeDecode
@CodeDecode 3 жыл бұрын
Will try to increase voice from next videos 👍👍 thanks for the suggestion 👍👍
@letscodewithshivam
@letscodewithshivam 24 күн бұрын
11:06
@arvindrajput2336
@arvindrajput2336 3 жыл бұрын
Good content..
@CodeDecode
@CodeDecode 3 жыл бұрын
Thank you
@tanveer.shaikh
@tanveer.shaikh 2 жыл бұрын
can we get this ppt?
@premamalar8550
@premamalar8550 2 жыл бұрын
I cannot understand object is compared with this keyword.... How it will work like compare e1 and e2?? Please explain it mam..
@CodeDecode
@CodeDecode 2 жыл бұрын
This keyword is used to point to current object. When used in a class the current class's object is denoted by this keyword.
@premamalar8550
@premamalar8550 2 жыл бұрын
@@CodeDecode ok mam
@CodeDecode
@CodeDecode 2 жыл бұрын
No problem prema 🙂👍 keep learning keep shining ⭐✨⭐✨
@rakeshgouda970
@rakeshgouda970 3 жыл бұрын
I have one doubt in overriding equals , Employee e=(Employee)o; Return this.id ==e.id; Why you are casting Can't we use directly the below return this.id==o.id;
@kishorems8954
@kishorems8954 2 жыл бұрын
Compiler will throw an error saying Type mismatch if you don't cast it
@dheerajgupta6795
@dheerajgupta6795 Жыл бұрын
Hi Mam, Need Help please reply Thanks, Dheeraj
@CodeDecode
@CodeDecode Жыл бұрын
Hi Dheeraj. How are you.
@anmolgangwal9236
@anmolgangwal9236 2 жыл бұрын
what is the need of these methods i didnt understand ,
@user-ty8rl1nn4x
@user-ty8rl1nn4x 8 ай бұрын
Your all videos voice is low. please correct next time.
@CodeDecode
@CodeDecode 8 ай бұрын
Sure 😊
@shikhasrivastav9208
@shikhasrivastav9208 3 жыл бұрын
I still don't understand why it's important to override these two methods together
@CodeDecode
@CodeDecode 3 жыл бұрын
If u dont override hashcode method then even if objects are equal, different hash code will be generated and your equal objects will be stored in different hash buckets which is wrong. Is that clear?
@CodeDecode
@CodeDecode 3 жыл бұрын
Over riding equals method is obvious, if you want to check equality based on property value and not hash code or memory location then override equal method.
@CodeDecode
@CodeDecode 3 жыл бұрын
You want me to elaborate more?
@kshitijsinghsomvanshi
@kshitijsinghsomvanshi Жыл бұрын
If you don't override hashcode method, then both e1 and e2 despite being equal will end up in different memory location which is wrong. So this contract mean whenever you override equals method you should also override hashcode so that this scenario doesn't happen. If you try to run this program after overriding hashcode both objects will be in same memory location so shallow as well as deep comparison both will return "true"
@kshitijsinghsomvanshi
@kshitijsinghsomvanshi Жыл бұрын
@@CodeDecode I am amazed by your explanations. Keep up the good work mam :)
@start1learn-n171
@start1learn-n171 5 ай бұрын
Tq
@CodeDecode
@CodeDecode 5 ай бұрын
You’re welcome
I CAN’T BELIEVE I LOST 😱
00:46
Topper Guild
Рет қаралды 114 МЛН
Was ist im Eis versteckt? 🧊 Coole Winter-Gadgets von Amazon
00:37
SMOL German
Рет қаралды 38 МЛН
02. Equals and HashCode Contract & Different Variations
11:19
WebEncyclop Tutorials
Рет қаралды 52 М.
.equals() vs. == in Java - The Real Difference
8:48
Coding with John
Рет қаралды 181 М.
#58 Object Class equals toString hashcode in Java
12:00
Telusko
Рет қаралды 93 М.
Мой инст: denkiselef. Как забрать телефон через экран.
0:54
Mastering Picture Editing: Zoom Tools Tutorial
0:52
Photoo Edit
Рет қаралды 506 М.
iPhone 15 Pro в реальной жизни
24:07
HUDAKOV
Рет қаралды 257 М.
Опять съемные крышки в смартфонах? #cmf
0:50