Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

What is Hashing techniques in java ?

Hashing is a process of converting an object into integer form by using the method hashCode() of obecjt class. Its necessary to orverride hashCode() and equals method properly for better performance of HashMap. Here I am taking key of my own class so that I can override hashCode() method to show different scenarios. My Key class is

//custom Key class to override hashCode()
// and equals() method

class Key
{
    String key;
    Key(String key)
    {
        this.key = key;
    }

    @Override
    public int hashCode()
    {
        int hash = (int)key.charAt(0);
        System.out.println("hashCode for key: "
                           + key +" = "+ hash);
        return hash;
    }

    @Override
    public boolean equals(Object obj)
    {
        return key.equals(((Key)obj).key);
    }
}

Here overrided hashCode() method returns the first character’s ASCII value as hash code. So whenever the first character of key is same, the hash code will be same. You should not approach this criteria in your program. You should overide hashcode() method depends on the requirement. It is just for demo purpose. As HashMap also allows null key, so hash code of null will always be 0.

Bucket location or Index Calculation in Hashmap?

Hash code of key may be large enough to create an array. hash code generated may be in the range of integer and if we create arrays for such a range, then it will easily cause outOfMemoryException. So we generate index to minimize the size of array. Basically following operation is performed to calculate index.

index = hashCode(key) & (n-1).

Below methos is used to find bucket location in hashMap.

static int indexFor(int h, int length) {
return h & (length - 1);
}
where n is number of buckets or the size of array and h is hashcode of object. In our example, I will consider n as default size that is 16.


This post first appeared on Java Programming Tutorials Online For Java Coder, please read the originial post: here

Share the post

What is Hashing techniques in java ?

×

Subscribe to Java Programming Tutorials Online For Java Coder

Get updates delivered right to your inbox!

Thank you for your subscription

×