HashCode.java


Below is the syntax highlighted version of HashCode.java from §4.4 Symbol Tables.


/******************************************************************************
 *  Compilation:  javac HashCode.java
 *  Execution:    java HashCode s
 *
 *  Computes the hash code of a string s and compares it against Java's
 *  built in hashcode method.
 *
 *  % java HashCode ishmael
 *
 ******************************************************************************/

public class HashCode {

    public static int hashCode(String s) {
        int hash = 0;
        for (int i = 0; i < s.length(); i++)
            hash = (31 * hash) + s.charAt(i);
        return hash;
    }

    public static void main(String[] args) {
        String s = args[0];
        StdOut.println("Java hashCode = " + s.hashCode());
        StdOut.println("Our  hashCode = " + hashCode(s));
    }
}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.