Pages

Monday, July 20, 2020

Java String hashCode() example

Java String hashCode()

1. Overview


In this String Methods series, You are going to learn hashcode() method of String class with example programs.

Java String hashCode() method returns the hash code for the String. Hash code value is used in hashing based collections like HashMap, HashTable etc. This method must be overridden in every class which overrides equals() method.

Java String hashCode() example

2. hashCode() Syntax


Syntax:

public int hashCode()

Returns integer value as hash of string. No exception is thrown.

3. hashCode() internals


The hash code for a String object is computed as below.

s[0]*31^(n-1) + s[1]*31^(n-2) + … + s[n-1]

where :

s[i] – is the index of character in the string
n – is the length of the string and finally
^ – indicates exponentiation


4. Java String hashCode() Example


package com.javaprogramto.strings;

public class StringHashcodeExample {

    public static void main(String[] args) {

        String str = "hello string fan";

        int hashValue = str.hashCode();

        System.out.println("hash code of string : "+hashValue);

        String newString = "this is a new string";

        int newStrHashValue = newString.hashCode();

        System.out.println("New string hash value : "+newStrHashValue);
    }
}


Output:

hash code of string : -1804800366
New string hash value : 1638601060


5. Can Java's hashCode produce same value for different strings?


Yes. 

A Java hash code is 32bits. The number of possible strings it hashes is infinite.

So yes, there will be collisions. The percentage is meaningless - there is an infinite number of items (strings) and a finite number of possible hashes.


package com.javaprogramto.strings;

public class StringHashcodeCheckExample {

    public static void main(String[] args) {

        String str1 = "FB";

        int hashCode1 = str1.hashCode();

        System.out.println("hash code of str 1 : " + hashCode1);

        String str2 = "FB";

        int hashCode2 = str2.hashCode();

        System.out.println("hash code of str 2 : " + hashCode2);

        if(hashCode1 == hashCode2){
            System.out.println("Hashcodes of str1 and str2 are same");
        } else{
            System.out.println("str1 and str2 hashcodes are not same");
        }
    }
}

Output:

hash code of str 1 : 2236
hash code of str 2 : 2236
Hashcodes of str1 and str2 are same

6. Conclusion


In this article, You've seen how to get the hashcode of the String. And also whether hashcode for two strings can be same ?

All examples are shown here are over Github.



Read More on String Methods


References:


No comments:

Post a Comment

Please do not add any spam links in the comments section.