Last updated 2004-06-28 by Roedy
Green ©1996-2004 Canadian Mind Products
Java definitions: 0-9 A B C D E F G H I J K L M N O P Q R S T U V W X Y Z
You are here : home : Java Glossary : H words : hashCode.
A Hashtable goes a step further, scrunching down the hashCode even further to an even smaller number that it can use to directly index an array, usually by dividing it by some (ideally prime) number and taking the remainder.
So if you had a Fruit object with a flavour and colour field, and you decided that any two objects with the same flavour were for all intents and purposes equal, you would define your equals and hashCode methods like this:
Here is another approach that would work better if you had two Strings in your object. It gives a different hash code for your two objects when:
// object1 has o1.string1 = "apple"; o1.string2 = "orange"; // and object2 has o2.string1 = "orange"; o2.string2 = "apple";
It works like this to combine hash codes of the fields in your object:
/** * hashCode that combines two strings * @return a hash code value on the pair of strings. */ public int hashCode() { int result = 17; result = 37 * result + string1.hashCode(); result = 37 * result + string2.hashCode(); // etc for all fields in the object return result; }
Here is roughly how String.hashCode works inside:
/** * simplified version of how String.hashCode works. * For the actual version see src.jar java/lang/String.java * @return a hash code value for this String. */ public int hashCode() { // inside the String is a char[] val that holds the characters. int hash = 0; int len = char.length(); for ( int i=0; i<len; i++ ) { hash = 31 * hash + val[i]; } return hash; }
Here is a fast hash algorithm you can apply to bytes, short, chars, ints, arrays etc. I used an assembler version of it it my BBL Forth compiler hashcode where it is essentially implemented in two instructions, ROL and XOR.
/** * Java version of the assembler hashCode used in the BBL Forth compiler. * @return a hash code value for the byte[] val byte array in this object. */ public int hashCode() { // byte[] val holds the data. int hash = 0; int len = val.length(); for ( int i=0; i<len; i++ ) { // rotate left and xor (very fast in assembler, a bit clumsy in Java) hash <<= 1; if ( hash < 0 ) { hash |= 1; } hash ^= val[i]; } return hash; }
If you know the key values in advance, it is possible to construct a hashCode function that has no collisions.
home |
Canadian Mind Products | |||
| mindprod.com IP:[24.87.56.253] | ||||
| Your IP:[80.134.30.163] | ||||
| You are visitor number 8220. | ||||
| Please send errors, omissions and suggestions | ||||
| to improve this page to Roedy Green. | ||||
| You can get a fresh copy of this page from: | or possibly from your local J: drive mirror: | |||
| http://mindprod.com/jgloss/hashcode.html | J:\mindprod\jgloss\hashcode.html | |||