





























Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!






























Overview
Scattering Hash Values Hash Function
Open Addressing Chaining
Sets Set B Set C Set A
Collection of elementswithout duplicates No ordering (i.e., no frontor back) Order in which elementsadded doesn’t matter
Offer the ability to find /remove element quickly Without searchingthrough all elements
How Do Sets Work in Java?
Need to define your own equals(Object) method Default equals( ) uses reference comparison I.e., a.equals(b)
a == b a, b equal only if reference to same object Many classes have predefined equals( ) methods Integer.equals( )
compares value of integer String.equals( )
compares text of string
Map Definition
Unordered collection of keys For each key, an associated object Can use key to retrieve object
Example A[“key1”] = … key1 key2 key3 key
Map Interface Methods
void put( Key, Object ) // inserts element Object get( Key ) // returns element void remove( Key ) // removes element Boolean containsKey( Key ) // looks for key Set keySet( ) // entire set of keys
Map Implementation
Two parallel arrays Unsorted Sorted Linked list Binary search tree Hash table
TreeMap
uses red-black (balanced) tree HashMap
uses hash table
Java Collections Map Hierarchy Map SortedMap AbstractMap TreeMap HashMap LinkedHashMap
Hashing
Array indexed using hash values Hash table A with size N Indices of A range from 0 to N-1 Store in A[ hashValue % N]
Hash Function
Hash value
32-bit signed int Default hash function
int hashCode( )
Must reduce hash value to 0..N – 1 Can use modulo operator Math.abs(hash value % N)
Scattering Hash Values
Produces good hash values Hash value = Math.abs((a * key.hashCode( )) % N) Where N is table size a is large prime number
Beware of % (Modulo Operator)
x % y == x – y * ( x / y )
–|y| < x % y < +|y|
Since Math.abs(Integer.MIN_VALUE) == Integer.MIN_VALUE! Will happen 1 in 2 32 times (on average) for random int values
Hash Function
Unique values for each key
0 1 2 3 4 5 6 7 8 9
Hash Function
Same hash value formultiple keys
0 1 2 3 4 5 6 7 8 9