The Department of Computer Science & Engineering |
STUART C. SHAPIRO: CSE
116 B
|
put(Object key, Object
value)
and get(Object key)
.
obj1.equals(obj2)
then obj1.hashCode() ==
obj2.hashCode()
Example:
bsh % int[] a = {2, 4, 6, 2, 7, 9}; bsh % a2 = new ArrayList(); bsh % b2 = new ArrayList(); bsh % for (int i=0; i<a.length; i++) a2.add(a[i]); bsh % for (int i=0; i<a.length; i++) b2.add(a[i]); bsh % print(a2); [2, 4, 6, 2, 7, 9] bsh % print(b2); [2, 4, 6, 2, 7, 9] bsh % print(a2 == b2); false bsh % print(a2.equals(b2)); true bsh % print(a2.hashCode()); 948636961 bsh % print(b2.hashCode()); 948636961
a2.hashCode()
= 948,636,961.) So every hash table has
some capacity, and the index used is actually
obj.hashCode() % capacity
.
key.hashCode() % capacity
, keys that are not content
equal may get the same index. This is called collision, and
some collision resolution stragegy is needed.
Closed hashing stores, at each position of the array, a bucket: a collection of all the values whose keys hash to this same array position. Any collection may be used for the buckets. A linked list is common. Another hash table is sometimes used, but this requires a second hash function.
equals
for comparison purposes.
HashMaps are Java's implementation of hash tables, as discussed above.
Since it is legal to store null
as a value, HashMaps have
a useful boolean containsKey(Object
key)
method.
HashSet implements a set by using a HashMap as
a bit vector (where the value is either true
or
false
), although it's probably implemented by just using
containsKey
.