What happens if we override only hashCode() in a class and use it in a Set?

前端 未结 5 749
既然无缘
既然无缘 2020-12-15 11:25

This may not be the real world scenario but just curious to know what happens, below is the code.

I am creating a set of object of class UsingSet. Accor

5条回答
  •  佛祖请我去吃肉
    2020-12-15 11:55

    Simply you can Assume hashcode and equals methods as a 2D search like:-

    Where Hashcode is the Rows and the object list is the Column. Consider the following class structure.

    public class obj
      {
        int Id;
        String name;
        public obj(String name,int id)
         {
             this.id=id;
             this.name=name;
         }
      }
    

    now if you create the objects like this:-

    obj obj1=new obj("Hassu",1);
    obj obj2=new obj("Hoor",2);
    obj obj3=new obj("Heniel",3);
    obj obj4=new obj("Hameed",4);
    obj obj5=new obj("Hassu",1);
    

    and you place this objects in map like this :-

        HashMap hMap=new HashMap();
       1. hMap.put(obj1,"value1");
       2. hMap.put(obj2,"value2");
       3. hMap.put(obj3,"value3");
       4. hMap.put(obj4,"value4");
       5. hMap.put(obj5,"value5");
    

    now if you have not override the hashcode and equals then after putting all the objects till line 5 if you put obj5 in the map as By Default HashCode you get different hashCode so the row(Bucket will be different). So in runtime memory it will be stored like this.

    |hashcode   | Objects   
    |-----------| --------- 
    |000562     | obj1 
    |000552     | obj2 
    |000588     | obj3
    |000546     | obj4
    |000501     | obj5
    

    Now if you create the same object Like :- obj obj6 = new obj("hassu",1); And if you search for this value in the map.like

    if(hMap.conaints(obj6)) 
    or 
    hMpa.get(obj 6);
    

    though the key(obj1) with the same content is available you will get false and null respectively. Now if you override only equals method. and perform the same content search key will also get the Null as the HashCode for obj6 is different and in that hashcode you wont find any key. Now if you override only hashCode method.

    You will get the same bucket (HashCode row) but the content cant be checked and it will take the reference checked implementation by Super Object Class. SO here if you search for the key hMap.get(obj6) you will get the correct hashcode:- 000562 but as the reference for both obj1 and obj6 is different you will get null.

提交回复
热议问题