/** * A demo of a hash function for Strings. */ public class StringHash { /** * This code computes the built-in hash function of the String * class (present as the hashCode method of the String class). * Computes a weighted sum of the individual letters of * the string (designed to evenly balance hash values among * different strings without biasing towards, e.g., * particular or smaller values). */ public static int stringHashCode(String s) { char[] chars = s.toCharArray(); int hash = 0; for (int i = 0; i < chars.length; i++) { hash = 31 * hash + chars[i]; } return hash; } /** * Given a string, print the hash value using the stringHashCode utility method * and the built-in hashCode method of the String class. */ private static void test(String s) { System.out.println("\"" + s + "\" hash code is " + stringHashCode(s)); System.out.println("\"" + s + "\" hash code (built-in) is " + s.hashCode()); } /** * Compute some String hash values. */ public static void main(String[] args) { test("Bowdoin"); test("College"); test("the"); test(""); test("computer science is the best"); } }