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

Viewed 1311

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?

2 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.

Let's guess the output of below expression:

Object obj = new Object();
System.out.println(obj.hashCode() == obj.hashCode());

Obviously true right? Because irrespective of you implementing the hashCode() or not, the consecutive hashCode() calls on the same instance will always return the same int value, provided you have not altered the state of the instance in-between.

A class once loaded into the JVM memory is also an instance by itself. Remember I'm not talking about the instances you create by new keyword, Employee.class itself is an instance of java.lang.Class class which is created implicitly by JVM when any class having reference to Employee.class is loaded or you can take as an example the class instance that will be returned by Class.forName("Employee.class") method.

You can even access all Object class methods on the class instances too. Such as Employee.class.toString(), Employee.class.getClass(), etc. Now in your statement #2, both of your instances returns the reference to the same class instance that's why your expression returns true.

Related