Friday, May 31, 2013

Hash code for Strings

HashCode

A brief introduction about  hashcode:-


  1. Hash code integer representation of the memory  address  of the object
  2. If two objects are equal  by equals method then their hashcode must be necessarily equal,vice-versa may need not be true.
Hash code generation for strings  is based on  below  formula,it overrides Hashcode method of Object Class
  • 
    
s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]
Where s[0] is the first character(ASCII value) in the string etc... 
           n is the length of the String
Note:- Hash code of empty string is zero,
  1. Example 
    1. String s4=new String("a");
    2. System.out.println(s4.hashCode()+"  HashCode Value");
OutPut:- 97  HashCode Value


No comments:

Post a Comment

Like and Share