-1

Anyone tell me how java create hashcode internally ?

package swain.javainterviewhub.blogspot.in;


    public class JavaInterviewHub {

        public static  void main(String[] args) {

           String str="Alex";
           System.out.println(str.hashCode());
        }

    }
    Output:2043454

Key Hashcode Algorithm Hashcode

Alex A(1) + L(12) + E(5) + X(24)=42

Sitansu
  • 3,225
  • 8
  • 34
  • 61
  • possible duplicate of [What is an object's hash code if hashCode() is not overridden?](http://stackoverflow.com/questions/2237720/what-is-an-objects-hash-code-if-hashcode-is-not-overridden) – Kedar Parikh Aug 24 '15 at 10:28
  • For a more challenging problem, try generating haiku (5 syllable, 7 syllable, 5 syllables) as a String which has a hashCode() of 0. ;) – Peter Lawrey Aug 24 '15 at 11:14

2 Answers2

3

From the documentation:

The hash code for a String object is computed as

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

You can also look at the source for additional information (Oracle JDK 8u45 here).

public int hashCode() {
    int h = hash;
    if (h == 0 && value.length > 0) {
        char val[] = value;

       for (int i = 0; i < value.length; i++) {
            h = 31 * h + val[i];
        }
        hash = h;
    }
    return h;
} 
Mena
  • 47,782
  • 11
  • 87
  • 106
0

Hash code generation in Java depends on the type of the object in question. For Strings, the algorithm is described in the Java docs (here).

Returns a hash code for this string. The hash code for a String object is computed as

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

using int arithmetic, where s[i] is the ith character of the string, n is the length of the string, and ^ indicates exponentiation. (The hash value of the empty string is zero.)

kviiri
  • 3,282
  • 1
  • 21
  • 30