I have below code in main method of a class
Map<Integer, String> names = new HashMap<>();
Map<Integer, String> names2 = new HashMap<>();
names.put(1,"Pratik");
names2.put(1,"Pratik");
System.out.println(names.equals(names2));
System.out.println(names.hashCode());
System.out.println(names2.hashCode());
System.out.println(names == names2);
When I run the code, the output is as below:
true -1896349258 -1896349258 false
The problem is if hashcode return same value for both the objects, then why does ( names == names2 ) returns false ?
Expecting the comparison by == to come out as true for objects having same hashcode value.
CodePudding user response:
From the official docs of hashCode()
:
It is not required that if two objects are unequal according to the
equals
method, then calling thehashCode
method on each of the two objects must produce distinct integer results.
If it is not required for equals
, it can't be required for ==
.
CodePudding user response:
The equality operator or "==" compares two objects based on memory reference. so "==" operator will return true only if two object reference it is comparing represent exactly same object otherwise "==" will return false.
So your == is returning false as you have two different objects created using new resides in two different memory locations.
Now regarding hashcode value ideally the values should be different as per below java docs.
As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the JavaTM programming language.)
Maybe HashMap class by default overrides its hashcode method to calculate hashcode based on map contents.