You can simply use the hashcode and equals methods as a 2D search, for example: -
Where the Hashcode is the rows and the list of objects 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 such objects: -
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 these objects on the map as follows: -
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 redefined hashcode and are equal, after you put all the objects up to line 5, if you put obj5 on the map, because by default HashCode you get a different hashCode, so the line (Bucket will be different). Thus, during operation, the memory will be saved as follows.
|hashcode | Objects |-----------| --------- |000562 | obj1 |000552 | obj2 |000588 | obj3 |000546 | obj4 |000501 | obj5
Now, if you create the same Like object: - obj obj6 = new obj ("hassu", 1); And if you are looking for this value on map.like
if(hMap.conaints(obj6)) or hMpa.get(obj 6);
although the key (obj1) with the same contents is available, you will get false and null respectively. Now, if you override only the equals method. and to execute the same content search key will also get Null, since the HashCode for obj6 is different and you will not find any key in this hash code. Now, if you override only the hashCode method.
You will get the same bucket (HashCode string), but the content cannot be verified, and it will perform a standard check on the Super Object Class. SO here, if you are looking for the key hMap.get (obj6), you will get the correct hash code: - 000562, but since the link for obj1 and obj6 is different, you will get zero.