210 likes | 490 Views
JCF Hashmap & Hashset. JCF HashMap stores <Key, Value> pairs in a hash table. Example: HashMap<String, Student> students; //String is the key //Student is the value Key/Value pairs are stored in a Map.Entry object public class HashMap<K, V> implements Map <K, V>
E N D
JCF Hashmap & Hashset CS-2851Dr. Mark L. Hornick
JCF HashMap stores <Key, Value> pairs in a hash table • Example:HashMap<String, Student> students;//String is the key//Student is the value • Key/Value pairs are stored in a Map.Entry object public class HashMap<K, V> implements Map<K, V> extends AbstractMap<K, V> CS-2851Dr. Mark L. Hornick
JCF HashMap Implements methods such as • put(k,v) – insert value v with key k into the table • get(k) – return the value associated with key k • remove(k) – remove entry associated with key k • containsKey(k) – search for entry with key k • containsValue(v) – search for entry with value v • size() • clear() CS-2851Dr. Mark L. Hornick
HashMap’s advantage is overall performance • Specifically, performance for the following operations is O(k); that is, constant time: • put(k,v) – insert value v with key k into the table • get(k) – return the value associated with key k • remove(k) – remove entry associated with key k • containsKey(k) – search for entry with key k CS-2851Dr. Mark L. Hornick
Performance is gained in exchange for memory utilization efficiency • Hash tables map keys to table indices • Some keys map to the same table index • Some indices remain unmapped CS-2851Dr. Mark L. Hornick
The JCF HashMap collision handling mechanism • At index 873 in the table, store the linked list of all elements whose keys hash to 873 • This is called chaining • It implements a simple singly-linked list CS-2851Dr. Mark L. Hornick
As chains get long, performance degrades to O(M) • M is the number of entries chained together • To maintain good performance, once a JCF HashMap becomes 75% full, it is resized • All indices are recalculated • Chains are removed or reduced CS-2851Dr. Mark L. Hornick
Another collision handler • In Open Address hashing, when a collision occurs, the next available index is used to store the key/value • This leads to some interesting practical implementation problems (see the text) CS-2851Dr. Mark L. Hornick
HashSets CS-2851Dr. Mark L. Hornick
A HashSet is an unordered Collection in which the Value is also the Key • All Values in a HashSet must be unique • Since Values are the Keys • The HashSet class has all of the methods in the Collection interface (rather than Map) • add, remove, size, contains, … • plus toString (inherited from AbstractCollection) CS-2851Dr. Mark L. Hornick