A hash function is a reproducible method of turning some kind of data into a (relatively) small number that may serve as a digital "fingerprint" of the data. The algorithm "chops and mixes" (i.e., substitutes or transposes) the data to create such fingerprints. The fingerprints are called hash sums, hash values, hash codes or simply hashes. (Note that hashes can also mean the hash functions.) Hash sums are commonly used as indices into hash tables or hash files.
Using hash codes rather than unique values can substantially speed or simplify code.
P Ventura
Ranch Hand
Joined: Jan 24, 2007
Posts: 42
posted
0
hashcode is used in collections. It's used to find a bucket where your object will be inserted. If you don't understand this, read something about Collections and Maps and all will be clear.
See the API documentation for the method java.lang.Object.hashCode():
Returns a hash code value for the object. This method is supported for the benefit of hashtables such as those provided by java.util.Hashtable.
Collection classes such as Hashtable, HashMap and HashSet use hashcodes for efficiency.
The hashCode() method in a class has to adhere to specific rules, which are described in the API documentation for the hashCode() method in class Object. Note that if you write a class with an equals() method, you should also implement the hashCode() method according to the rules.
Keep in mind that although hashcodes are sometimes considered "digital fingerprints" (as referenced in the Wikipedia article), they are not necessarily unique. Two unequal objects might have the same hashcode and still comply with the hashcode contract (described in the API under Object's hashCode method). On the other hand, equal objects should always return the same hashcode. It's important to understand this distinction for the exam.
"We're kind of on the level of crossword puzzle writers... And no one ever goes to them and gives them an award." ~Joe Strummer sscce.org