The hashcode was introduced in java for comparison of the objects in java.
To compare two or more objects using the .equals() method their hash code must be same.
Yeah it's true in our previous blog we discussed about the differences between == and .equals().
The one step ahead this concept will give you a sneak peek into the background working of .equals().
So what exactly is hashcode ?
Hash Codes are used in data sorting.In data sorting we assign a hash code to every object if two objects have same hash code they are put together in same tuple.
Consider this example ,
We are using a simple hash code algorithm.
Note: This is not a real hashcode algorithm it is just an example as real hashcode algorithms are way tougher.
Suppose we want to store names Alex,May and Amy.
So, hashcode
ALEX=1+12+5+24= 42
MAY=13+1+25= 39
AMY=1+13+25= 39
So the names having same hash codes are put together in same tuple.
So May and Amy are in same tuple but Alex will be in another tuple.
So,when you search about May it will calculate it's hash code which is 37 so it will start searching in the tuple which is marked 37.
It is also true that you can override the hash code and equals of any class.
But remember to maintain the consistency of the program the overriding must be such that it follows our basic rule i.e two objects are equal if their hash code id equal.
These are some of the basics of hash codes they have a large application in data sorting in Array Lists etc.
No comments:
Post a Comment