Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

employee.hashCode() Vs employee.getClass().hashcode() in Java

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?

like image 558
Pankaj Avatar asked Sep 15 '18 13:09

Pankaj


People also ask

What is the importance of hashCode () and equals () methods?

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.

What is hashCode () method in Java?

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.

What happens if we override only hashCode and not equals?

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.

Can two objects have same hashCode?

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.


1 Answers

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.

like image 54
Mureinik Avatar answered Oct 11 '22 01:10

Mureinik