What is the meaning of hashCode in Java?

What is the meaning of hashCode in Java?

What is the meaning of hashCode in Java?

What is the meaning of hashCode in Java?
  • For every object a unique number generated by JVM which is nothing but hashCode.
  • Hashcode won’t represent an address of the object.
  • JVM will use hashCode while saving the object into hashing related data structures like HashTable, HashSet, HashSet, etc..
  • The main advantage of saving object based on HashCode is search operation will become easy(the most powerful search algorithm up today is Hashing).
  • If you are giving the chance to object class HashCode method it will generate HashCode based on the address of the object. It doesn’t mean hashcode represent the address of the object.
  • HashCode is a method that returns an integer to confirm whether two objects are equal. Such objects are mainly HashMaps and HashSets. The objects are only equal if their hashCode methods return equal integer values.
  • The hashcode of a Java Object is simply a number, it is 32-bit signed int, that allows an object to be managed by a hash-based data structure. We know that hash code is an unique id number allocated to an object by JVM. But actually speaking, Hash code is not an unique number for an object. If two objects are equals then these two objects should return same hash code. So we have to implement hashcode() method of a class in such way that if two objects are equals, ie compared by equals() method of that class, then those two objects must return same hash code.
  • Based on our requirement we can override hashcode method in our class to generate our own hashcode.
  • Overriding hashCode() is said to be proper if an only if for every object we have to generate a unique number as hashcode.
class Employee{
 int rollNo;
 String name:
 public int hashCode()
 {
   retrun 100; //inproper
 }
}

This is an improper way of overriding hashcode() because for all student object we are generating the same number as hashcode. 

class Employee{
 int rollNo;
 String name;
 public int hashCode()
  {
    return id;
  }
}

This is a proper way of overriding hashcode() because we are generating a different hashcode for every object. 

Leave a Reply

Your email address will not be published. Required fields are marked *

*