hashCode() method is used to get a unique integer for given object. This integer is used for determining the bucket location, when this object needs to be stored in some HashTable like data structure. By default, Object’s hashCode() method returns and integer representation of memory address where object is stored.
equals() method, as name suggest, is used to simply verify the equality of two objects. Default implementation simply check the object references of two objects to verify their equality.
- Always use same attributes of an object to generate hashCode() and equals() both. As in our case, we have used employee id.
- equals() must be consistent (if the objects are not modified, then it must keep returning the same value).
- Whenever a.equals(b), then a.hashCode() must be same as b.hashCode().
- If two objects have the same hashcode, they may or may not be equal.
- If you override one, then you should override the other.
The “==” operator
In Java, when the “==” operator is used to compare 2 objects, it checks to see if the objects refer to the same place in memory. In other words, it checks to see if the 2 object names are basically references to the same memory location. A very simple example will help clarify this:
String obj1 = new String("xyz");
String obj2 = new String("xyz");
obj1==obj2 is FALSE
String obj1 = new String("xyz");
// now obj2 and obj1 reference the same place in memory
String obj2 = obj1;
obj1==obj2 is TRUE
The equals() method
equals method is actually meant to compare the contents of 2 objects, and not their location in memory.
String obj1 = new String("xyz");
String obj2 = new String("xyz");
obj1.equals(obj2) is TRUE
by default equals() will behave the same as the “==” operator and compare object locations. But, when overriding the equals() method, you should compare the values of the object instead.
The Java String class actually overrides the default equals() implementation in the Object class – and it overrides the method so that it checks only the values of the strings, not their locations in memory. This means that if you call the equals() method to compare 2 String objects, then as long as the actual sequence of characters is equal, both objects are considered equal.