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
  • НаукаНаука

Комментарии • 131

  • @jiniamitra7593
    @jiniamitra7593 3 года назад +10

    Main point is equals method will get called when for key hashcode value is same.

  • @ragakaplish501
    @ragakaplish501 2 года назад +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 🙂👍

  • @yoshitamahajan353
    @yoshitamahajan353 3 года назад +1

    Thanks this is best explanation over the net..

    • @CodeDecode
      @CodeDecode  3 года назад

      M glad you find it helpful

  • @harshinredzone
    @harshinredzone Год назад +1

    Helpful video. Thank you ma'am.

  • @satishhawalppagol1892
    @satishhawalppagol1892 3 года назад +4

    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 11 месяцев назад +1

      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.

  • @vinieas2373
    @vinieas2373 3 года назад +1

    Surely Aasaam Your explanation and all the topics all very cleared mam

  • @menaceasif
    @menaceasif 3 года назад +1

    Thanks for ur explanation ma'am.... Really helped me to understand it better...

  • @krishnanitturkar2793
    @krishnanitturkar2793 Год назад +1

    Amazing explaination mam, Thanks.

  • @rajajodhani8024
    @rajajodhani8024 2 года назад +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

  • @DKRamnani
    @DKRamnani 5 месяцев назад

    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.

  • @rahuldebnath3919
    @rahuldebnath3919 2 года назад +1

    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.

  • @naveenkumarmaddala7830
    @naveenkumarmaddala7830 4 года назад +3

    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 года назад +3

      Sure. I will cover hash code and it's working in detail very soon.

  • @manasdeora4601
    @manasdeora4601 3 года назад +1

    Very properly explained.

  • @sudarshankalvankar1827
    @sudarshankalvankar1827 2 года назад +1

    Thanks for supporting us .Video is really useful to understand the concept.

  • @soumyaranjan6196
    @soumyaranjan6196 3 года назад +1

    your explanation is very clear.Please make a video on internals of hashmap

    • @CodeDecode
      @CodeDecode  3 года назад +1

      Sure will upload that soon

  • @manishchavan1760
    @manishchavan1760 2 года назад +1

    Thanks for explain.

  • @aditis4993
    @aditis4993 2 года назад +1

    I can't tell you enough how awesome you are for making these videos. Thank you

    • @CodeDecode
      @CodeDecode  2 года назад

      Thanks Aditi 🙂🙂👍👍

  • @subhadipde7636
    @subhadipde7636 2 года назад +1

    Awesome explanation ..

  • @unemployedcse3514
    @unemployedcse3514 10 месяцев назад +1

    It was asked in my interview ❤

  • @reeltorealworld5660
    @reeltorealworld5660 4 года назад +2

    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  4 года назад +3

      Any private variable can be accessed in other class using objects and getter setter methods.

  • @srijanbiswas
    @srijanbiswas 2 года назад +1

    shouldnt we add @Override annotation for overridng hashcode() ??

  • @saritachoudhury461
    @saritachoudhury461 5 месяцев назад

    your video contents are really great and helpful. But just a suggestion can you please minimize the usage of "NOTHING BUT" while explaining.

  • @mohitg1
    @mohitg1 3 года назад +1

    thanks for the video.. you're doing a great job. all the very best & keep it up.

  • @AmitKumar-pw1ln
    @AmitKumar-pw1ln 3 года назад +1

    Thanks a lot !! This cleared my doubts

    • @CodeDecode
      @CodeDecode  3 года назад

      You are most welcome....

  • @Naveenraj093
    @Naveenraj093 3 года назад +1

    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👍

  • @rohitkapade1130
    @rohitkapade1130 2 года назад +2

    thank you so much

  • @dystopianNinja1289
    @dystopianNinja1289 3 года назад +2

    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 Год назад

      @CodeDecode , you need to deep compare based on all fields. not only id right?

  • @gauravkhare1836
    @gauravkhare1836 4 месяца назад +1

    best 👍

  • @076_mohammadbelalansari4
    @076_mohammadbelalansari4 3 месяца назад +1

    Great mam

  • @silpavig6838
    @silpavig6838 4 года назад +2

    Mam can you please make video on hash map interview questions including custom hash map topic

    • @CodeDecode
      @CodeDecode  4 года назад

      Sure will upload this topic soon

  • @amarthyaseshu683
    @amarthyaseshu683 3 года назад +1

    thanks for sharing, very helpful while writing tests

  • @EasyTechStudios
    @EasyTechStudios 4 года назад +2

    Thanks 🙌🙌

  • @gettoshubhi
    @gettoshubhi 3 года назад +1

    Please make video on multithreading in java and Strings

  • @arunkumark3832
    @arunkumark3832 Месяц назад

    i tried to print the hash code it is different?

  • @jasper5016
    @jasper5016 2 года назад +4

    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
      ruclips.net/p/PLyHJZXNdCXscoyL5XEZoHHZ86_6h3GWE1

  • @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.

  • @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 3 года назад

      Compiler will throw an error saying Type mismatch if you don't cast it

  • @ishansingh306
    @ishansingh306 7 месяцев назад

    Help me understand if(o == THIS){ return true; } i didn't understand it. this is a keyword how did you use it here?

  • @amitsh5413
    @amitsh5413 3 года назад

    Is there any video related to internal implementation of hash code on your channel

  • @shubhamkandpal-fb4ip
    @shubhamkandpal-fb4ip 2 месяца назад

    What she told for Prime number thing .
    @Override
    public int hashCode() {
    int hash = getClass().hashCode();
    hash = 31 * hash + id;
    return hash;
    }

  • @miraclepraveen2423
    @miraclepraveen2423 Год назад

    Maam you have implement equals() but didn't tell about hashcode() how to work

  • @manoharsitaram3300
    @manoharsitaram3300 4 года назад +1

    Nice. Can u make the video on immutable class and spring framework.

    • @CodeDecode
      @CodeDecode  4 года назад

      That's a nice suggestion. Will make the video on that too soon

  • @ANILKUMAR-cc3lb
    @ANILKUMAR-cc3lb 2 года назад

    What if I'd is alphanumeric we cannot return it directly in hashcode right?

  • @ANILKUMAR-cc3lb
    @ANILKUMAR-cc3lb 2 года назад

    Will shallow comparison gives false still?

  • @Naanu_kartik
    @Naanu_kartik Год назад +1

    Thanks 🙏

  • @VivekPatel-ux6vi
    @VivekPatel-ux6vi 4 года назад +1

    In third step of equals method do we need to compare all the property of that class?

    • @CodeDecode
      @CodeDecode  4 года назад +2

      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 года назад +1

      @@CodeDecode thanks for your response, it's really helpful.

  • @rupeshkumarbhavsar6093
    @rupeshkumarbhavsar6093 3 года назад +1

    can we use instanceOf operator instead of get class name for comparison?

  • @SumanthReddyAdudoodla
    @SumanthReddyAdudoodla 8 месяцев назад +1

    respect !!!

  • @seemadnimje1574
    @seemadnimje1574 3 года назад +2

    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 👍👍

  • @shankarpatilsp
    @shankarpatilsp 3 года назад +1

    Thanks!!

  • @singhji4149
    @singhji4149 Год назад

    Hello Mam,
    After overriding equals and hashcode why e1==e2 is giving false?

    • @wasifkhan544
      @wasifkhan544 11 месяцев назад

      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.

  • @premamalar8550
    @premamalar8550 2 года назад +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 года назад +1

      @@CodeDecode ok mam

    • @CodeDecode
      @CodeDecode  2 года назад +1

      No problem prema 🙂👍 keep learning keep shining ⭐✨⭐✨

  • @pavanpavankalyan2790
    @pavanpavankalyan2790 Год назад

    How to write testcases for equals method

  • @yoshitamahajan353
    @yoshitamahajan353 3 года назад +1

    Hi can u please share internal implementation of trees, treemap...

  • @start1learn-n171
    @start1learn-n171 5 месяцев назад +1

    Tq

  • @josephfifstones
    @josephfifstones 2 года назад +1

    good content thanks :)

  • @theprofessor252
    @theprofessor252 Год назад +1

    Legend

  • @pecan8470
    @pecan8470 2 года назад +1

    saved my life

    • @CodeDecode
      @CodeDecode  2 года назад

      Glad to do that 😃👍👍

  • @ShinAkuma
    @ShinAkuma 2 года назад +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 👍🙂

  • @arvindrajput2336
    @arvindrajput2336 3 года назад +1

    Good content..

  • @tanveer.shaikh
    @tanveer.shaikh 2 года назад

    can we get this ppt?

  • @anmolgangwal9236
    @anmolgangwal9236 2 года назад

    what is the need of these methods i didnt understand ,

  • @dheerajgupta6795
    @dheerajgupta6795 2 года назад +1

    Hi Mam,
    Need Help please reply
    Thanks,
    Dheeraj

    • @CodeDecode
      @CodeDecode  2 года назад

      Hi Dheeraj. How are you.

  • @viswareddy-x4n
    @viswareddy-x4n 11 месяцев назад +1

    Your all videos voice is low. please correct next time.

  • @shikhasrivastav9208
    @shikhasrivastav9208 3 года назад +2

    I still don't understand why it's important to override these two methods together

    • @CodeDecode
      @CodeDecode  3 года назад +1

      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 года назад +1

      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 :)

  • @letscodewithshivam
    @letscodewithshivam 3 месяца назад

    11:06

  • @start1learn-n171
    @start1learn-n171 8 месяцев назад +1

    Tq