Learnerslesson
   JAVA   
  SPRING  
  SPRINGBOOT  
 HIBERNATE 
  HADOOP  
   HIVE   
   ALGORITHMS   
   PYTHON   
   GO   
   KOTLIN   
   C#   
   RUBY   
   C++   

Java - HashCode and HashCollision


HashCode

Just imagine there is a large hall and the desks and benches in the hall are placed in only
a single row. Benches are marked from roll numbers 1 to 500.

Now, there are a group of students and we need to calculate their rollno based on their names.
And make them sit on their seats based on their roll numbers.

But how? Let's mark the alphabets from 1 to 26. i.e. A is 1, B is 2, C is 3 and so on.

Let's suppose there is a guy 'SAM' and we will make his roll number by adding the letters
in his names.

i.e. S - 19, A - 1, M - 13.

So, the added value of SAM is 19+1+13=33.

So, Sam is assigned roll no 33.

Similarly if 'ABY' comes, her rollno would be A-1, B-2, y-23. i.e. 1+2+23=26.

Thus, Aby would be assigned rollno 26.

So, in this way roll numbers would be assigned to all the students in that group.
And that is Hashing and the rollno we are calculating is called its HashCode.

Now, if someone comes and asks you to find 'ABY', simply you will calculate the roll number
by adding the letters of her name and find her seat.


Hash Collision


But stop, think for a while. There can be a guy named 'BAY'.

So, his roll number would be: B-2, A-1, Y-23. i.e 2+1+23=26.

Strange! Bay and Aby both have roll number 26.

This is called a Hash Collision where two elements(or guys in this case) have the same roll numbers. So, one more seat will be reserved for 'BAY' with number 26 attached on the seat.

But there can be a situation where a large group of students are assigned roll number 26.

So, in that case you have to go to seat number 26 and ask the names of each and every students.

So the logic of calculating HashCode(roll number in this case) should be in such a way that hash collisions(equal roll numbers in this case) does not occur.