Section 6.5:
Stewy Slocum and Michael Appel
Hashing
Hashing
#
What is Hashing?
Stewy: Greetings, plebian.
Michael: It is I, scrublord.
Stewy: What is Hashing?
Michael: Hashing is a technique that is used to efficiently store and retrieve data in an array.
Stewy: So what does the hashing?
Michael: A hash function calculates a hash code to denote the items location in the array.
Benefits of Hashing
-
Unloading memory - large and complex variables in object can be stored in an array rather than many variables
-
Speed - retrieving values from a hash requires only one check, eliminating the need to loop through a whole array to find one value
How does one hash?
1. Write a Hash Function
Converts raw data into an index that can be stored in an array.
public class HashEntry {
private int key;
private int value;
HashEntry(int key, int value) {
this.key = key;
this.value = value;
}
public int getKey() {
return key;
}
public int getValue() {
return value;
}
}2. Pass Values to Hash
Determine the values you will store and run them through the hash function.

3. Store Data in Array according to hash code
Store the data in the array at the index returned by the hash function.
| "Hello" | "Michael" | "Is" | "Plebian" | ||
|---|---|---|---|---|---|
| 0 | 1 | 2 | 3 | 4 | 5 |
4. Retrieve data from the Array
A client contains the hash codes, and retrieves the data by returning the information at the hash code's index in the array.
Things to Remember
-
Avoid Collisions, when two values generate and occupy the same hash code
-
Create an array twice the size of the # of elements that will be stored
-
There are ways to deal with collisions, as will be discussed later in the course
Section 6.5: Hashing
By Stewy Slocum
Section 6.5: Hashing
- 221