Hash Table Time Costs - Hash Functions - The Map Interface and Implementations
Hash Table Time Costs - Hash Functions - The Map Interface and Implementations
19
= n/m
1
1
U n,m 1+
2
2 1
S n,m
1
1
1+
2 1
Unsuccessful search
Successful search
These are quite good, if is not too close to 1 (that is, if the
table is not too full).
For example if =.75, then Un = 8.5 and Sn = 2.5
Note that these are O(1), independent of n
4
n
U n,m
m
n 1
S n,m
1 1
2m
2
Unsuccessful search
Successful search
5
Hash Functions
A hash function takes a key of some type as argument, and
returns an integer
A hash table method will call the hash function, take the integer
it returns mod the size of the table to produce an index in
range, and perform collision resolution as required
What is a good hash function? It depends on the type of the
key
J
74 * 313 +
a
97 * 312
v
+ 118 * 311
a
+ 97 * 310
Contracts for equals() and hashCode() say that two equal objects
must have the same hash code
But when are two collections equal?
10
11
12
/**
* This class implements a hashtable, which maps keys to values.
* Any non-null object can be used as a key or as a value.
* <p>
* To successfully store and retrieve objects from a hashtable, the
* objects used as keys must implement the <code>hashCode</code>
* method and the <code>equals</code> method.
*/
public class HashMap<K,V> implements Map<K,V>, Cloneable {
13
/**
* The total number of entries in the hash table.
*/
private int count;
/**
* The table is rehashed when count exceeds this threshold.
*/
private int threshold;
/**
* The maximum load factor allowed for this hash table.
*/
private float loadFactor;
14
HashMap constructors
/**
* Constructs a new, empty hashtable with the specified
* initial capacity and the specified load factor.
*
* @param initialCapacity the initial capacity of the table
* @param loadFactor a number between 0.0 and 1.0.
* @exception IllegalArgumentException if the initial
* capacity is less than zero, or if the load factor
* is less than or equal to zero.
*/
public HashMap(int initialCapacity, float loadFactor) {
if ((initialCapacity < 0) || (loadFactor <= 0.0)) {
throw new IllegalArgumentException();
}
table = new Entry[initialCapacity];
threshold = (int) (initialCapacity * loadFactor);
this.loadFactor = loadFactor;
}
16
17
18
19
21
23
Next time
Final review
Reading: everything!
25