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; } 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()); } public static void main(String[] args) { test("Bowdoin"); test("College"); test("the"); test(""); test("computer science is the best"); } }