I have below program.
Employee employee1 = new Employee("Raghav1", 101);
Employee employee2 = new Employee("Raghav", 100);
// #1
System.out.println(employee1.hashCode() == employee2.hashCode());
// #2
System.out.println(employee1.getClass().hashCode() == employee2.getClass().hashCode());
The statement 1 returns false
as both employee objects are different but why the statement 2 returns true
.
Can anyone explain the difference between the above statements?
An object hash code value can change in multiple executions of the same application. If two objects are equal according to equals() method, then their hash code must be same. If two objects are unequal according to equals() method, their hash code are not required to be different.
The hashCode() method is defined in Java Object class which computes the hash values of given input objects. It returns an integer whose value represents the hash value of the input object. The hashCode() method is used to generate the hash values of objects.
Only Override HashCode, Use the default Equals: Only the references to the same object will return true. In other words, those objects you expected to be equal will not be equal by calling the equals method. Only Override Equals, Use the default HashCode: There might be duplicates in the HashMap or HashSet.
1) If two objects are equal (i.e. the equals() method returns true), they must have the same hashcode. 2) If the hashCode() method is called multiple times on the same object, it must return the same result every time. 3) Two different objects can have the same hash code.
The first statement compares the hash code of two employee instances. This is probably a bad implementation of the hashCode()
method, since it seems as though both instances should be equal, and hence should have equal hash codes.
The second statement gets the class of each instance and compares the hash codes of the classes. Since both employee1
and employee2
are instances of Employee
, they both have the same class, and you're just comparing two calls to the same hashCode()
method, which are bound to return the same value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With