Equals and Hashcode Contract in Java [Important Java Interview Question] | Code Decode
HTML-код
- Опубликовано: 4 окт 2024
- 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/u...
Course Description Video :
yt.openinapp.c...
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 : www.youtube.co...
Linkedin : / codedecodeyoutube
Instagram : / codedecode25
--------------------------------------------------------------------------------------------------------------------------------------
#equalsandhashcode #equalsandhashcodecontract #java - Наука
Main point is equals method will get called when for key hashcode value is same.
most easy and we explained video very very thanks a lot most helpful video cleared my all doubts keep up the good work .
Thanks a lot Raga 🙂👍
Thanks this is best explanation over the net..
M glad you find it helpful
Helpful video. Thank you ma'am.
you're welcome
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.
Mostly asked questions in Interview..👍
please let me know the answer once you have got the answers. Thank you :)
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.
Surely Aasaam Your explanation and all the topics all very cleared mam
Thanks vini 👍👍
Thanks for ur explanation ma'am.... Really helped me to understand it better...
M glad it helps 🙃
Amazing explaination mam, Thanks.
🙂🙂Thanks 👍👍
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
Thanks Raja🙂👍
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.
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 ?
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.
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.
Sure. I will cover hash code and it's working in detail very soon.
Very properly explained.
Thanks Manas 👍👍
Thanks for supporting us .Video is really useful to understand the concept.
you're welcome
your explanation is very clear.Please make a video on internals of hashmap
Sure will upload that soon
Thanks for explain.
You're welcome manish
I can't tell you enough how awesome you are for making these videos. Thank you
Thanks Aditi 🙂🙂👍👍
Awesome explanation ..
Thanks
It was asked in my interview ❤
😊
Mam u made d variable private in employee class..plz tell me how we will acess or sort dis value in another class...
Any private variable can be accessed in other class using objects and getter setter methods.
shouldnt we add @Override annotation for overridng hashcode() ??
your video contents are really great and helpful. But just a suggestion can you please minimize the usage of "NOTHING BUT" while explaining.
thanks for the video.. you're doing a great job. all the very best & keep it up.
Thanks.... :-)
Thanks a lot !! This cleared my doubts
You are most welcome....
Hi can you please do a video on how hash code works internally please do pratical implementation
Sure Naveen. Will do that👍
thank you so much
you're welcome rohit
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
Yes
@@CodeDecode how is it possible? Employee name can be anything with same id for different objects. Right?
@CodeDecode , you need to deep compare based on all fields. not only id right?
best 👍
Thanks
Great mam
Thanks
Mam can you please make video on hash map interview questions including custom hash map topic
Sure will upload this topic soon
thanks for sharing, very helpful while writing tests
👍👍🙂🙂
Thanks 🙌🙌
Please make video on multithreading in java and Strings
Sure 👍👍
i tried to print the hash code it is different?
This is a really good video. Thanks. Can you please cover some other core java topics like Collections or Generics?
We have covered most of them
ruclips.net/p/PLyHJZXNdCXscoyL5XEZoHHZ86_6h3GWE1
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.
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;
Compiler will throw an error saying Type mismatch if you don't cast it
Help me understand if(o == THIS){ return true; } i didn't understand it. this is a keyword how did you use it here?
Is there any video related to internal implementation of hash code on your channel
What she told for Prime number thing .
@Override
public int hashCode() {
int hash = getClass().hashCode();
hash = 31 * hash + id;
return hash;
}
Maam you have implement equals() but didn't tell about hashcode() how to work
Nice. Can u make the video on immutable class and spring framework.
That's a nice suggestion. Will make the video on that too soon
What if I'd is alphanumeric we cannot return it directly in hashcode right?
Will shallow comparison gives false still?
Thanks 🙏
you're welcome
In third step of equals method do we need to compare all the property of that class?
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.
If you still are not clear Lemme know I will eloborate more with real world examples.
@@CodeDecode thanks for your response, it's really helpful.
can we use instanceOf operator instead of get class name for comparison?
Yes
respect !!!
Thanks
Hi, Your explanation is great, but the audio is too low. Thanks.
Will try to increase voice from next videos 👍👍 thanks for the suggestion 👍👍
Thanks!!
👍
Hello Mam,
After overriding equals and hashcode why e1==e2 is giving false?
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.
I cannot understand object is compared with this keyword.... How it will work like compare e1 and e2?? Please explain it mam..
This keyword is used to point to current object. When used in a class the current class's object is denoted by this keyword.
@@CodeDecode ok mam
No problem prema 🙂👍 keep learning keep shining ⭐✨⭐✨
How to write testcases for equals method
Hi can u please share internal implementation of trees, treemap...
Sure
Tq
Welcome
good content thanks :)
you're welcome yusuf
Legend
❤️
saved my life
Glad to do that 😃👍👍
New drinking game: Take a shot every time she says "nothing but the".
JK, nice tutorials.
Will try to reduce usage. Thanks for the suggestion 👍🙂
Good content..
Thank you
can we get this ppt?
what is the need of these methods i didnt understand ,
Hi Mam,
Need Help please reply
Thanks,
Dheeraj
Hi Dheeraj. How are you.
Your all videos voice is low. please correct next time.
Sure 😊
I still don't understand why it's important to override these two methods together
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?
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.
You want me to elaborate more?
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"
@@CodeDecode I am amazed by your explanations. Keep up the good work mam :)
11:06
Tq
You’re welcome