class: center, middle, title-slide # CSCI-UA 102 ## Data Structures
## Hash Tables .author[ Instructor: Joanna Klukowska
] .license[ Copyright 2020 Joanna Klukowska. Unless noted otherwise all content is released under a
[Creative Commons Attribution-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-sa/4.0/).
Background image by Stewart Weiss
] --- layout:true template: default name: section class: inverse, middle, center --- layout:true template: default name: breakout class: breakout, middle --- layout:true template:default name:slide class: slide .bottom-left[© Joanna Klukowska. CC-BY-SA.] --- template: section # Maps and Why We Want Them --- template: slide ## What Is a Map? A __map__ (also called a __dictionary__ or an __associative array__) stores __`(key, value)` pairs__. You give it a __key__, and it gives you back the __value__ that goes with that key. -- You use maps every day: | key | value | where | |-----------------------|-------------------------------|--------------------| | a person's name | their phone number | your phone's contacts | | a word | its definition | a dictionary | | a NetID (`"ab123"`) | the student's record | the registrar's system | | a website name (`nyu.edu`) | the server's IP address | the internet's DNS | | a product's barcode | its name and price | a store's checkout | -- Two rules: - __every key appears at most once__ (two contacts cannot have the same name in your phone), - __values can repeat__ (two people can share a phone number). --- ## The Basic Operations A map supports three main operations: .with-pic[ .text[ - __put(key, value)__ - store `value` under `key` (if `key` is already there, its old value is __replaced__), - __get(key)__ - look up the value stored under `key` (or report that `key` is not in the map), - __remove(key)__ - delete `key` and its value. ] .pic[
] ] -- ``` put("ab123", "Ada Byron") put("gh456", "Grace Hopper") put("at789", "Alan Turing") get("gh456") --> "Grace Hopper" get("xy000") --> not found remove("ab123") ``` -- Notice that we never ask *where* the pair is stored (no indexes, no "first" or "last" element). We only ever ask using the __key__. --- ## A First Map in Java ```java import java.util.HashMap; import java.util.Map; Map
names = new HashMap<>(); // keys: NetIDs, values: names names.put("ab123", "Ada Byron"); names.put("gh456", "Grace Hopper"); names.put("at789", "Alan Turing"); System.out.println(names.get("gh456")); // Grace Hopper System.out.println(names.get("xy000")); // null (no such key) names.put("ab123", "Ada Lovelace"); // same key: replaces the old value System.out.println(names.get("ab123")); // Ada Lovelace System.out.println(names.containsKey("at789")); // true names.remove("at789"); System.out.println(names.size()); // 2 ``` - `Map
` is the interface: `K` is the type of the keys, `V` is the type of the values. - `HashMap` is the class that implements it, using a __hash table__ (today's topic). --- ## Example: Counting Words .with-pic[ .text[ __Task:__ for a long text (say, a whole novel stored as an array `words`), count how many times each word appears. ] .pic[
] ] -- ```java Map
counts = new HashMap<>(); // word -> how many times we saw it for (String word : words) { if (counts.containsKey(word)) { // seen it before: counts.put(word, counts.get(word) + 1); // add 1 to its count } else { // first time: counts.put(word, 1); // its count is 1 } } System.out.println(counts.get("whale")); // how many times "whale" appears ``` -- - the map grows as we see new words; we never have to search for a word ourselves, - a novel has hundreds of thousands of words, so `get` and `put` are called hundreds of thousands of times __this only works well if `get` and `put` are fast__. --- ## How Fast Can a Map Be? .with-pic[ .text[ Back to the registrar: 50,000 student records, looked up by NetID millions of times a day. We could implement a map with any of the structures we already know: ] .pic[
] ] | structure | find | insert | remove | |-----------------------|------------|------------|------------| | unsorted array / list | O(N) | O(1) | O(N) | | sorted array | O(log N) | O(N) | O(N) | | balanced BST | O(log N) | O(log N) | O(log N) | -- __Can we do all three in O(1)?__ -- Arrays already give us O(1) access, *if we know the index*: `A[i]`. So the real question is: can we turn a key into an array index? --- ## Idea 1: Use the Key as the Index .with-pic[ .text[ If keys were small integers, this would be easy. Seats in a lecture hall are numbered 0 to 199: ```java Student[] seats = new Student[200]; seats[42] = s; // insert: O(1) Student t = seats[42]; // find: O(1) seats[42] = null; // remove: O(1) ``` ] .pic[
] ] -- But real keys are rarely like that. Keys may be - __too big:__ 8-digit student ID numbers would need an array of 100,000,000 locations to store 50,000 students (more than 99.9% of it empty), - __not integers:__ `"ab123"`, `"Italy"`, a `Point`, a `Date`, ... - __negative.__ --- ## Idea 2: Compute the Index from the Key Use a function that turns __any__ key into an index in a __small__ array: .center[
] - `hashCode()` turns the key into an `int` (any `int`, possibly negative), - `% M` squeezes that `int` into the range `0 ... M-1`, where `M` is the array size. -- This combination of an array and a function that computes indexes from keys is a __hash table__. `put`, `get` and `remove` all start the same way: compute the index, go straight to that array location. --- ## The Catch: Collisions .with-pic[ .text[ - There are far more possible keys than array locations, so (pigeonhole principle) __some different keys must end up at the same index__. This is called a __collision__. ] .pic[
] ] -- .with-pic[ .text[ - How soon does this happen? __Quick poll:__ what is your birthday? (don't worry, this poll does not collect your name or netID, just the day and month)
(see the results)
] .pic[
] ] -- - With 365 possible birthdays and only __23__ people, the chance that two of them share a birthday is already over 50%. (The *birthday problem*.) Collisions happen long before the table is full. -- __Questions__ 1. How do we compute a good index from a key? (__hash functions__) 2. What do we do when two keys land on the same index? (__collision resolution__) 3. What do we do when the table gets too full? (__rehashing__) --- template:section # Hash Tables in Java --- ## `Map
` Interface - Java provides a `Map` interface and several possible implementations of it. - https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Map.html -- - `interface Map
` - __an object that maps keys of type `K` to values of type `V`__ (`K` and `V` are generic types, this is a good example of using non-standard generic letters that have their own meaning in the `Map` structure - you can use whatever letters you wish when you implement your own hash tables) - __a map cannot contain duplicate keys; each key can map to at most one value__ -- - methods we are going to be using and you should be familiar with: - __`V put(K key, V value)`__ associates `value` with `key`; returns the previous value associated with `key`, or `null` if there was no mapping for `key` - __`V get(Object key)`__ returns the value to which `key` is mapped, or `null` if this map contains no mapping for the `key` - __`V remove(Object key)`__ removes the mapping for `key` if it is present; returns the previous value associated with `key`, or `null` if there was no mapping for `key` - __`boolean containsKey(Object key)`__ returns `true` if this map contains a mapping for `key` - __`Set
keySet()`__ returns a `Set` view of the keys contained in this map --- ## `Hashtable
` class - https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Hashtable.html - `class Hashtable
extends Dictionary
implements Map
` - This class implements a hash table, which maps keys to values. - Any non-null object can be used as a `key` or as a `value`. - To successfully store and retrieve objects from a hash table, the objects used as keys must implement the `hashCode` method and the `equals` method. -- .important[ __This class is considered a legacy class.__ It inherits from the [`Dictionary`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/Dictionary.html) class, which has been labeled obsolete for some time. Use `HashMap` instead, or [`ConcurrentHashMap`](https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/concurrent/ConcurrentHashMap.html) if you need thread safety. ] --- ## `HashMap
` class - https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/HashMap.html - `class HashMap
extends AbstractMap
implements Map
` - This class implements a hash table, which maps keys to values. - __The `HashMap` class is roughly equivalent to `Hashtable`, except that it is unsynchronized and permits nulls__ (one `null` key and any number of `null` values). - To successfully store and retrieve objects from a hash table, the objects used as keys must implement the `hashCode` method and the `equals` method. -- - `HashMap` does not guarantee any order of its keys: iterating over `keySet()` may produce the keys in a different order than they were inserted, and that order can change when the table is rehashed. --- template:section # Implementing Hash Tables --- ## Storing a Hash Table - __What is used for storing a hash table?__ Usually an __array__. (But there might be other structures stored within each location of the array.) -- - __What is the type of such array?__ A single array location must hold a `(key, value)` pair. This could be implemented as a node containing the two values: ```java class HashNode
{ private K key; private V value; } ``` In practice, such nodes are often linked in some way, so there may be a need to also store references to other nodes (we will see this with separate chaining). -- - __Everything else__ follows from the three questions from the beginning of the lecture: 1. how to compute the index from the key - __hash function__ (next), 2. what to do when two keys get the same index - __collision resolution__, 3. what to do when the array gets too full - __rehashing__. --- template: section # Hash Function ## (and Java's `hashCode`) --- name:hash-function ## Hash Function - Based on unique keys we need to be able to compute the location in the array (or hash table) at which the given `(key, value)` combination can be stored. - Why can't we just use the key itself as an index? Well, it might be - too big, - negative, or - not an integer. -- .center[
] --- template:hash-function .center[
] --- template:hash-function .center[
] --- template:hash-function .center[
] --- template:hash-function .center[
] --- template:hash-function - __Properties of a good hash function__: _A hash function is supposed to chop up its argument and construct a value out of the chopped up little pieces._ To be good, a hash function should be - __easy to compute__ (for speed), - __repeatable__, and - __disperse keys__ evenly (as if at random) throughout the table, keeping the number of keys that map to the same index as small as possible. --- ## Good Hash Function - __Easy to compute__ generally means that the function is an O(1) operation, practically independent of the input size and hash table size. - For example, if the function tried to find all of the prime factors of a given number in order to compute the hash function, this would not be easy to compute. - Being easy to compute is a fuzzy concept. -- - __Repeatable__ means that making two calls to a hash function with the same argument should produce the same result. - It would be much easier to compute values quickly and disperse them well if you could use random numbers, but there would be no way to recover the data from the hash table once it is saved there. -- - __Dispersing the keys evenly__ means that every index is (about) equally likely to be chosen, even when the keys themselves follow a pattern (all even, all ending in 00, all starting with `"user"`, ...). - For example, if the hash table is of size 1000 and there are 200 keys in it, each index should hold about 0.2 keys on average, and no index should get many more than the others. -- .center80[ .important[ In principle, if the set of keys is finite and known in advance, we can construct a perfect hash function, one that maps each key to a unique index. In practice, the set of keys is rarely known at the time of writing the program and may not be finite. ]] --- ## From `hashCode()` to an Index Getting an index from a key is a __two-step__ process: 1. `key.hashCode()` - turns the key into an `int` (the same for every table), 2. __compression__ - turns that `int` into an index `0 ... M-1` for a table of size `M`. -- __Pitfall__ `hashCode()` can be __negative__, and in Java `%` keeps the sign: ```java int h = "polygenelubricants".hashCode(); // -2147483648 (Integer.MIN_VALUE) int bad1 = h % 7; // -2 --> ArrayIndexOutOfBoundsException int bad2 = Math.abs(h) % 7; // still -2: Math.abs(Integer.MIN_VALUE) is negative! ``` -- Safe ways to compute the index: ```java int index = Math.floorMod(h, M); // always in 0 ... M-1 int index = (h & 0x7fffffff) % M; // clear the sign bit, then % ``` -- Java's `HashMap` uses table sizes that are powers of two and computes ```java index = (h ^ (h >>> 16)) & (M - 1) ``` the XOR (`^` operator) mixes the high bits into the low bits, and `& (M - 1)` keeps only the low bits, which is the same as `% M` for `M` a power of two (and is never negative). --- ## Good Hash Functions: `String` class - Java provides a method called `hashCode()` for all its classes that can be used as keys into hash tables (`String`, `Integer`, ...). - For example, the `hashCode()` method in the `String` class is implemented as follows (this is the Java 8 version; newer versions store the characters differently, but compute the same value): .smaller[ ```java /** * Returns a hash code for this string. The hash code for a String object is computed as * s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1] * using integer arithmetic, where s[i] is the i'th character of the string, * n is the length of the string, and ^ indicates exponentiation. * (The hash value of the empty string is zero.) * @return a hash code value for this object. */ public int hashCode() { int h = hash; if (h == 0 && value.length > 0) { char val[] = value; for (int i = 0; i < value.length; i++) { h = 31 * h + val[i]; } hash = h; } return h; } ``` ] - For long strings `31 * h` overflows, which is why string hash codes are often negative. --- ## Good Hash Functions: `Integer` class ```java /** * Returns a hash code for this {@code Integer}. * * @return a hash code value for this object, equal to the * primitive {@code int} value represented by this * {@code Integer} object. */ public int hashCode() { return value ; } ``` -- This is fast, but it means that __patterns in the keys become patterns in the indexes__. For example, keys `100, 200, 300, ..., 1500` in a table with `M = 100`: __every key goes to index 0__. --- ## Good Hash Functions: `Double` class ```java /** * Returns a hash code for a {@code double} value. * * @param value the value to hash * @return a hash code value for a {@code double} value. */ public static int hashCode(double value) { long bits = doubleToLongBits(value); return (int)(bits ^ (bits >>> 32)); } ``` -- - a `double` has 64 bits, but a hash code is an `int` with only 32 bits, - simply casting `(int) bits` would keep the low 32 bits and __throw away the high 32 bits__, and the high bits hold the sign, the exponent, and the most significant digits of the number, - `bits ^ (bits >>> 32)` XORs the high half into the low half, so __all 64 bits affect the hash code__. --- ## What the Shift and XOR Do Think of the 64 bits of the `double` as two 32-bit halves, `H` (high) and `L` (low): ``` bits = [ H | L ] bits >>> 32 = [ 0 | H ] shift right by 32: H moves into the low half bits ^ (bits >>> 32) = [ H | H ^ L ] XOR: a bit is 1 if exactly one of the two bits is 1 (int)(bits ^ (bits >>> 32)) = H ^ L the cast keeps only the low 32 bits ``` -- So the hash code is `H ^ L`: every bit of the `double` has a say in the result. -- __Why it matters:__ for many common values the low half `L` is all zeros: | value | bits (in hex) | `(int) bits` | `(int)(bits ^ (bits >>> 32))` | |-------|---------------|--------------|-------------------------------| | `1.0` | `3FF00000 00000000` | `0` | `1072693248` | | `2.0` | `40000000 00000000` | `0` | `1073741824` | | `0.5` | `3FE00000 00000000` | `0` | `1071644672` | With just the cast, all of these values would collide. -- .smaller[Why XOR and not AND or OR? AND produces mostly 0s, and OR mostly 1s. XOR is equally likely to give 0 or 1, so it keeps the hash codes spread out.] --- ## The `hashCode()` and `equals()` Contract - __If `a.equals(b)` is `true`, then `a.hashCode() == b.hashCode()` MUST be true.__ -- - __If hashCode is different, the objects are definitely not equal.__ (The opposite is not true: two different objects may have the same hash code. That is a collision.) -- - __When you override `equals`, you must also override `hashCode` to maintain the contract.__ - Why? - If you override equals but not hashCode, your object might get lost in the map (put in bucket A, but looked for in bucket B). --- ## Breaking the Contract .smaller[ ```java class Point { private int x, y; public Point(int x, int y) { this.x = x; this.y = y; } @Override public boolean equals(Object o) { if (!(o instanceof Point)) return false; Point p = (Point) o; return x == p.x && y == p.y; } // no hashCode() --> uses Object's hashCode(), which is different for every object // even if the two objects are equal according to equals() } ------ Map
map = new HashMap<>(); map.put(new Point(1, 2), "treasure"); System.out.println(map.get(new Point(1, 2))); // null (almost always!) ``` ] -- - the two `Point(1, 2)` objects are equal, but have different hash codes, so `get` looks in the wrong place, - __fix:__ add your own `hashCode()` method that is consistent with `equals()` ```java @Override public int hashCode() { return Objects.hash(x, y); } ``` --- ## Using `Objects.hash` `java.util.Objects.hash(...)` combines several fields into __one__ hash code. Pass it the __same fields__ that `equals()` compares: ```java @Override public int hashCode() { return Objects.hash(x, y); } ``` -- What it computes (the same idea as `String.hashCode()`, with each field playing the role of a character): ```java int result = 1; for (Object field : fields) // here: x, then y result = 31 * result + (field == null ? 0 : field.hashCode()); return result; ``` -- For a `Point`, `x` and `y` are boxed to `Integer`, whose hash code is the value itself, so $$\texttt{Objects.hash(x, y)} = 31 \cdot (31 \cdot 1 + x) + y = 961 + 31x + y$$ - `new Point(1, 2).hashCode()` is `994`, - `new Point(2, 1).hashCode()` is `1024`. --- ## Why Use `Objects.hash`? - __Hard to get wrong.__ The "obvious" hash functions are poor: - `x + y`: `(1, 2)` and `(2, 1)` collide, and so does every point on the line `x + y = 10`, - `x * y`: every point with a `0` coordinate gets hash code `0`. Multiplying by 31 makes the __order__ of the fields matter, just like `"ab"` and `"ba"` get different hash codes. -- - __Handles `null` fields:__ a `null` field counts as `0` instead of throwing a `NullPointerException` (matters for fields like `String name`). -- - __Easy to keep consistent with `equals`:__ if you add a field to the class, add it to both `equals()` and the `Objects.hash(...)` call. --- ## Updating a Key After It Is in the Map - The index for a key,value pair is computed from the key. If the key is changed after it is in the map, its hash code changes, and the map will look for it in the wrong place. -- .smaller[ ```java // assume Point has equals() and hashCode() (using Objects.hash(x, y)) and a setter: // public void setX(int x) { this.x = x; } Map
map = new HashMap<>(); Point p = new Point(1, 2); map.put(p, "treasure"); // stored at the index computed from (1, 2) p.setX(5); // the key itself changes: now it is (5, 2) System.out.println(map.get(p)); // null: looks at the index for (5, 2) System.out.println(map.get(new Point(1, 2))); // null: right index, but the key stored there // is now (5, 2), not equal to (1, 2) System.out.println(map.size()); // 1: the pair is still in the map, but lost ``` ] -- - __Never change a key after it is in the map.__ --- template: section # Collision Resolution --- ## What happens when two things map to the same location? There are different ways of handling situations in which two keys map to the same location (called collision): -- - __closed addressing__ (also known as __open hashing__) - allows multiple `(key, value)` pairs to be stored in a single array location, -- - __open addressing__ (also known as __closed hashing__) - finds an alternative location for the `(key, value)` pair, if the first location is occupied. --- ## Closed addressing .with-pic[ .text[ - __separate chaining__ - put each `(key, value)` pair that maps to the same array location in a linked list (*chain* or *bucket*) that starts at that array location. If implemented well, the linked lists remain short on average. ] .pic[
] ] -- .smller[ - Java implementation detail: when a chain (linked list) gets too long (default threshold is 8), Java transforms that specific list into a balanced binary search tree (a red-black tree) - provided the table already has at least 64 locations; otherwise it resizes the table instead. This improves the worst-case search time in that chain from $O(N)$ to $O(\log N)$. ] --- ## Open addressing - __linear probing__ - if the location `h = hash(key)` is occupied, try `h + 1`, if that is occupied, try `h + 2`, and so on (wrapping around the end of the array), - __quadratic probing__ - if the location `h = hash(key)` is occupied, try the location 1 space away (`h + 1^2`), if that is occupied, try the location 4 spaces away (`h + 2^2`), then 9 spaces away (`h + 3^2`), and so on (the offset is the square of the attempt number, always measured from the original location `h`, wrapping around the end of the array), - __double hashing__ - like linear probing, but the step size is computed from the key by a __second__ hash function, so different keys take different steps. .smaller[In all of these, we need to handle retrieving elements from the hash table in a special way - they may not be in the locations computed by the hash value of the key. If the `(key, value)` pair is not found at the location computed by the hash function, we have to check the other places in which the collision resolution method might have placed them.] --- name:example_separate ## Example: collisions with separate chaining - key type `int`, value type is `String` - table size M = 5 - hash function `hash(key) = key % M ` - collision resolution: separate chaining (linked lists) --- template:example_separate ``` Index Table Content ********************* 0 null 1 null 2 null 3 null 4 null ``` --- template:example_separate ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] -> null <-- hash(11) = 1 2 null 3 null 4 null ``` - `put(11, "A")` - `hash(11) = 11 % 5 = 1` - collision: no - insert (11, "A") at index 1 --- template:example_separate ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] -> null 2 [ 7 | "B" ] -> null <-- hash(7) = 2 3 null 4 null ``` - `put(7, "B")` - `hash(7) = 7 % 5 = 2` - collision: no - insert (7, "B") at index 2 --- template:example_separate ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] -> null 2 [ 7 | "B" ] -> [ 12 | "C" ] -> null <-- hash(12) = 2 3 null 4 null ``` - `put(12, "C")` - `hash(12) = 12 % 5 = 2` - collision: yes, index 2 has other key-value pairs already - walk the list to make sure 12 is not there yet, then insert (12, "C") at the end of the list at index 2 --- template:example_separate ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] -> null 2 [ 7 | "B" ] -> [ 12 | "C" ] -> [ 22 | "D" ]-> null <-- hash(22) = 2 3 null 4 null ``` - `put(22, "D")` - `hash(22) = 22 % 5 = 2` - collision: yes, index 2 has other key-value pairs already - insert (22, "D") at the end of the list at index 2 --- template:example_separate ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] -> null 2 [ 7 | "B" ] -> [ 12 | "C" ] -> [ 22 | "D" ]-> null 3 null 4 null ``` - If we now run `get(22)` - how many comparisons need to be made? - what value is returned? --- template:example_separate ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] -> null 2 [ 7 | "B" ] -> [ 12 | "C" ] -> [ 22 | "D" ]-> null 3 null 4 null ``` - If we now run `get(22)` - how many comparisons need to be made? __3, once we find that 22 belongs in the chain at index 2, we need to compare 22 to keys of the other key-value pairs: 7, 12 and finally 22__ - what value is returned? __D__ --- template:example_separate ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] -> null 2 [ 7 | "B" ] -> [ 22 | "D" ]-> null <-- node with 12 unlinked 3 null 4 null ``` - If we now run `remove(12)` - `hash(12) = 12 % 5 = 2`, walk the chain at index 2: 7 (no), 12 (yes) - unlink the node from the list (just like removing from any linked list) and return `"C"` -- - __nothing else needs to be done__: `get(22)` still walks the chain at index 2 and finds 22. (Keep this in mind: removing from open addressing tables will __not__ be this easy.) --- name:example_linear ## Example: collisions with linear probing - key type `int`, value type is `String` - table size M = 5 - hash function `hash(key) = key % M ` - collision resolution: linear probing --- template:example_linear ``` Index Table Content ********************* 0 null 1 null 2 null 3 null 4 null ``` --- template:example_linear ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] <-- hash(11) = 1: empty, insert 2 null 3 null 4 null ``` - `put(11, "A")` - `hash(11) = 11 % 5 = 1` - collision: no - insert (11, "A") at index 1 --- template:example_linear ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] <-- hash(7) = 2: empty, insert 3 null 4 null ``` - `put(7, "B")` - `hash(7) = 7 % 5 = 2` - collision: no - insert (7, "B") at index 2 --- template:example_linear ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] <-- hash(12) = 2: occupied 3 [ 12 | "C" ] <-- try 2+1 = 3: empty, insert 4 null ``` - `put(12, "C")` - `hash(12) = 12 % 5 = 2` - collision: yes, index 2 has another key-value pair already - resolve collision: probe the next index (2+1), it's available - insert (12, "C") at index 3 --- template:example_linear ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] <-- hash(22) = 2: occupied 3 [ 12 | "C" ] <-- try 2+1 = 3: occupied 4 [ 22 | "D" ] <-- try 2+2 = 4: empty, insert ``` - `put(22, "D")` - `hash(22) = 22 % 5 = 2` - collision: yes, index 2 has another key-value pair already - resolve collision: probe the next index (2+1), another collision - resolve second collision: probe the next index (2+2), it's available - insert (22, "D") at index 4 --- template:example_linear ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] 3 [ 12 | "C" ] 4 [ 22 | "D" ] ``` - If we now run `get(22)` - how many array locations need to be checked? - what value is returned? --- template:example_linear ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] <-- hash(22) = 2: key 7, keep going 3 [ 12 | "C" ] <-- key 12, keep going 4 [ 22 | "D" ] <-- key 22: found ``` - If we now run `get(22)` - how many array locations need to be checked? __3 locations at index 2, 3, and 4__ - what value is returned? __D__ --- template:example_linear ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] 3 [ 12 | "C" ] 4 [ 22 | "D" ] ``` - If we now run `put(3,"E")` - how many collisions will occur? - what index would it be placed in? --- template:example_linear ``` Index Table Content ********************* 0 [ 3 | "E" ] <-- wrap around to 0: empty, insert 1 [ 11 | "A" ] 2 [ 7 | "B" ] 3 [ 12 | "C" ] <-- hash(3) = 3: occupied 4 [ 22 | "D" ] <-- try 4: occupied ``` - If we now run `put(3,"E")` - how many collisions will occur? __2 since the hash(3) = 3 (first collision), then we check index 4 (another collision), and finally check index 0 (no collision)__ - what index would it be placed in? __index 0, since we wrap to the front of the array__ -- __Note 1: Linear probing tends to produce clusters (more on this in a moment).__ -- __Note 2: In practice, we do not want the table to be full as above.__ --- template:example_linear ``` Index Table Content ********************* 0 [ 3 | "E" ] 1 [ 11 | "A" ] 2 [ 7 | "B" ] <-- hash(12) = 2: key 7, keep going 3 [ 12 | "C" ] <-- key 12: found 4 [ 22 | "D" ] ``` - Let's run `remove(12)` - how do we find where the value matching 12 is? -- - hash (12) = 12 % 5 = 2, but the key stored at index 2 is NOT 12 -- - check the next index, the key at index 3 is 12, so we remove it and return the value -- - what do we put at index 3 now? --- template:example_linear ``` Index Table Content ********************* 0 [ 3 | "E" ] 1 [ 11 | "A" ] 2 [ 7 | "B" ] 3 null <-- what if we simply set it to null? 4 [ 22 | "D" ] ``` - Let's run `get(3)` - how do we find where the value matching 3 is? -- - hash (3) = 3 % 5 = 3, and index 3 is empty, so ... 3 is not in the table? -- - __wrong!__ 3 is at index 0. It got there by probing *past* index 3 when index 3 was occupied. -- **When we use open addressing, we need to be able to keep track of indexes that _used to_ have values. The `get` and `remove` algorithms treat them as if they were occupied when searching for a key.** --- template:example_linear .with-pic[ ``` Index Table Content ********************* 0 [ 3 | "E" ] <-- key 3: found 1 [ 11 | "A" ] 2 [ 7 | "B" ] 3 [ DELETED ] <-- hash(3) = 3: a tombstone, keep going 4 [ 22 | "D" ] <-- key 22, keep going ``` .pic[
] ] - Instead of `null`, `remove` leaves a special marker, often called a __tombstone__ (`DELETED`). - Let's run `get(3)` - how do we find where the value matching 3 is? - hash (3) = 3 % 5 = 3, index 3 holds a tombstone, so we continue to index 4, and then index 0 where we find key = 3 and return string E -- - `put` __can reuse__ a tombstone location for a new key (after checking that the key is not already further along). - tombstones are thrown away when the table is rehashed. --- ## Searching with Open Addressing When looking for a key, we follow the __same probe sequence__ that `put` would have followed, and stop when - we find the key (__found__), or - we reach a location that was __never used__ (`null`): if the key were in the table, `put` would have placed it here or earlier (__not found__), or - we have checked every location (__not found__). A tombstone (`DELETED`) does __not__ stop the search. -- .smaller[ ```java public V get(K key) { int home = Math.floorMod(key.hashCode(), table.length); for (int i = 0; i < table.length; i++) { int index = (home + i) % table.length; // linear probing: home, home+1, home+2, ... HashNode
node = table[index]; if (node == null) // never used: the key is not in the table return null; if (node != DELETED && node.key.equals(key)) // a tombstone never matches; keep going return node.value; } return null; // checked every location } ``` ] .smaller[`DELETED` is a single special node object, e.g. `private final HashNode
DELETED = new HashNode<>(null, null);`. For quadratic probing, only the line that computes `index` changes.] --- ## Clustering Look at this table of size 10 that uses linear probing (`X` = occupied): .center[
] If the next key's hash is equally likely to be any index, where will it end up? -- .center[
] __Index 4__ gets every key whose hash is 1, 2, 3, or 4; __index 7__ gets hashes 6 and 7. -- __The bigger a cluster gets, the more likely it is to grow even bigger.__ And every key whose hash lands in a cluster has to walk to the end of it. This is called __primary clustering__. -- - __quadratic probing__ fixes this for keys with *different* home indexes (they jump out of the cluster), but all keys with the *same* home index still follow the same sequence of locations (__secondary clustering__), - __double hashing__ fixes both (next). --- name:example_quad ## Example: collisions with quadratic probing - key type `int`, value type is `String` - table size M = 5 - hash function `hash(key) = key % M ` - collision resolution: quadratic probing --- template:example_quad ``` Index Table Content ********************* 0 null 1 null 2 null 3 null 4 null ``` --- template:example_quad ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] <-- hash(11) = 1: empty, insert 2 null 3 null 4 null ``` - `put(11, "A")` - `hash(11) = 11 % 5 = 1` - collision: no - insert (11, "A") at index 1 --- template:example_quad ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] <-- hash(7) = 2: empty, insert 3 null 4 null ``` - `put(7, "B")` - `hash(7) = 7 % 5 = 2` - collision: no - insert (7, "B") at index 2 --- template:example_quad ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] <-- hash(12) = 2: occupied 3 [ 12 | "C" ] <-- try 2+1^2 = 3: empty, insert 4 null ``` - `put(12, "C")` - `hash(12) = 12 % 5 = 2` - collision: yes, index 2 has another key-value pair already - resolve collision: probe the next index (2+1^2), it's available - insert (12, "C") at index 3 --- template:example_quad ``` Index Table Content ********************* 0 null <-- never tried! 1 [ 11 | "A" ] <-- tried at attempts i = 2, 3 2 [ 7 | "B" ] <-- tried at attempts i = 0, 5 3 [ 12 | "C" ] <-- tried at attempts i = 1, 4, 6 4 null <-- never tried! ``` - `put(22, "D")` - `hash(22) = 22 % 5 = 2` - collision: yes, index 2 has another key-value pair already -- - resolve collision: probe the next index (2+1^2) = 3, another collision -- - resolve second collision: probe the next index (2+2^2) % 5 = 6 % 5 = 1, another collision -- - resolve third collision: probe the next index (2+3^2) % 5 = 11 % 5 = 1, another collision -- - resolve fourth collision: probe the next index (2+4^2) % 5 = 18 % 5 = 3, another collision -- - resolve fifth collision: probe the next index (2+5^2) % 5 = 27 % 5 = 2, another collision -- - resolve sixth collision: probe the next index (2+6^2) % 5 = 38 % 5 = 3, another collision - insert (22, "D") at ??? --- template:example_quad ``` Index Table Content ********************* 0 null 1 [ 11 | "A" ] 2 [ 7 | "B" ] 3 [ 12 | "C" ] 4 null ```
**We cannot find a possible location for (22, "D") in this case!!!** - This is sometimes an issue with quadratic probing since it skips some possibly empty indexes. - Here, the squares `i^2 % 5` are only ever 0, 1, or 4, so starting from index 2 we can only reach indexes 2, 3, and 1. -- **TO DO: with table size M = 7 and quadratic probing, insert the keys 3, 10, 17, 24, and 31 (in this order)** - Where does each key go? Can 31 be placed, even though the table still has empty locations? - What is the load factor at the moment the insertion fails? .smaller[(Known result: if M is prime and the table is at most half full, quadratic probing always finds an empty location.)] --- ## Double Hashing - use a __second hash function__ to decide the __step size__ for each key: try `h`, `h + step`, `h + 2*step`, `h + 3*step`, ... (all `% M`) - for example, with `M = 5`: `hash(key) = key % 5` and `step(key) = 1 + key % 3` (the step must never be 0, and with a prime `M` every step size eventually reaches every location) -- Start with `11` and `7` in the table, then put three keys that __all have hash 2__: .smaller[ ``` Index Table Content ********************* 0 [ 17 | "F" ] <-- 17: step = 1 + 17 % 3 = 3, tries 2, 0 1 [ 11 | "A" ] 2 [ 7 | "B" ] 3 [ 12 | "C" ] <-- 12: step = 1 + 12 % 3 = 1, tries 2, 3 4 [ 22 | "D" ] <-- 22: step = 1 + 22 % 3 = 2, tries 2, 4 ``` ] -- - with linear or quadratic probing, all three keys would follow the __same__ path from index 2, - with double hashing, each takes its __own__ path: no primary and no secondary clustering. --- ## Who Uses What? Both approaches are used in real, widely used software: - __separate chaining__ - Java's `HashMap` and `HashSet` (with the switch to trees for long chains) -- - __open addressing__ - Java's `IdentityHashMap`: a linear-probing hash table; its documentation says that for many uses it is faster than `HashMap` - Python's `dict` and `set`: probe using a pseudo-random sequence computed from the hash code - Go's built-in `map` (since Go 1.24, 2025), Rust's `HashMap`, Google's C++ `absl::flat_hash_map`: all based on Google's __"Swiss Table"__ design, which probes small groups of slots at a time -- __Why open addressing?__ The pairs live directly in the array: no extra node objects and no `next` references to follow. Neighboring array locations sit next to each other in memory, and modern processors read memory in blocks, so checking the next location is very cheap. __Why separate chaining?__ Simpler to implement, removal is easy, and it degrades gracefully when the table gets full (load factor can even go above 1). --- template: section # Rehashing --- ## Growing the size of the table .with-pic[ .text[ - The __load factor__ is the number of elements divided by the size of the array: $$\text{load factor} = \dfrac{\text{number of elements}}{\text{capacity of the table}}$$ ] .pic[
] ] -- WARNING
The above definition uses the number of elements! (NOT the number of chains.) -- - How large can it be? - __separate chaining__: can go above 1 (chains just get longer), but performance drops; Java's `HashMap` keeps it below 0.75, - __open addressing__: must stay below 1 (every element needs its own location), and should be well below it, - __quadratic probing__: at most 0.5, to guarantee that an empty location can be found (with a prime table size). -- - When array becomes _too full_ (i.e. the load factor exceeds some predefined threshold), **all** the values stored in the table need to be __rehashed__ to a larger table. This is an O(N) operation! -- - But if the table __doubles__ (roughly) every time, rehashing happens rarely: after a rehash at size N, the next one only happens after about N more insertions. Spread over those insertions, the cost is O(1) per `put`. We say `put` takes __amortized__ O(1) time. --- ## How Full Is Too Full? Expected number of locations checked by `get` (standard estimates, assuming the hash function spreads keys evenly): | load factor | linear probing: found | linear probing: not found | chaining: found | chaining: not found | |------|------|-------|------|------| | 0.5 | 1.5 | 2.5 | 1.25 | 0.5 | | 0.75 | 2.5 | 8.5 | 1.4 | 0.75 | | 0.9 | 5.5 | 50.5 | 1.45 | 0.9 | .smaller[(linear probing: about $\frac{1}{2}\left(1 + \frac{1}{1 - \alpha}\right)$ when found and $\frac{1}{2}\left(1 + \frac{1}{(1 - \alpha)^2}\right)$ when not found; chaining: about $1 + \frac{\alpha}{2}$ and $\alpha$ key comparisons, where $\alpha$ is the load factor)] -- - separate chaining barely notices a fuller table, - linear probing gets __much__ slower as the table fills up: at 90% full, an unsuccessful search checks about 50 locations, twenty times more than at 50% full, - that is why open addressing tables rehash early, and why `HashMap`'s default threshold of 0.75 is a reasonable trade-off between memory and time. --- ### Example Consider a table of size 7 and integer keys (values not shown), using __linear probing__. Before each insertion we check: __would this insertion make the load factor greater than 0.75?__ If yes, we rehash first, then insert. ``` 0 1 2 3 4 5 6 ------------------------------------ | 21 | 15 | | 38 | | 12 | 76 | ------------------------------------ ``` $\text{load factor} = \frac{5}{7} = 0.714 $ -- `put(16)` - would result in $\text{load factor} = \frac{6}{7} = 0.857 > 0.75$, so we need to rehash first. -- Let's say that the hash table grows by the rule of $2\times \text{size} + 1$, then a new table will have size 15, and all the existing values need to be _rehashed_ to new locations - 21 % 15 = 6 - 15 % 15 = 0 - 38 % 15 = 8 - 12 % 15 = 12 - 76 % 15 = 1 --- ### Example (continued) After rehashing (load factor $\frac{5}{15} = 0.33$): ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ---------------------------------------------------------------------------- | 15 | 76 | | | | | 21 | | 38 | | | | 12 | | | ---------------------------------------------------------------------------- ``` -- Now `put(16)`: 16 % 15 = 1, a collision with 76. With linear probing, we try index 2, which is empty: ``` 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 ---------------------------------------------------------------------------- | 15 | 76 | 16 | | | | 21 | | 38 | | | | 12 | | | ---------------------------------------------------------------------------- ``` -- With __separate chaining__ instead, 16 would be added to the chain at index 1: `[76] -> [16] -> null`. --- ## The Worst Case .with-pic[ .text[ What if __every__ key hashes to the same index? - separate chaining: one long chain, every operation is O(N), - open addressing: one huge cluster, every operation is O(N). ] .pic[
] ] -- This can happen by accident (a bad hash function, keys with a pattern) or __on purpose__: - an attacker who knows the hash function can send a web server thousands of keys (for example, form field names) that all collide, and the server slows to a crawl. This is called a __hash flooding__ attack. -- Defenses used in practice: - Java 8 turns long chains into balanced trees, so the worst case becomes O(log N) per operation, - many languages (for example Python and Rust) use a __random seed__ in their string hash function, chosen when the program starts, so attackers cannot predict which keys collide. --- ## Summary .smaller[ | operation | average case | worst case | |------------|--------------|------------| | `get` | O(1) | O(N) (O(log N) in Java's `HashMap`) | | `put` | O(1) amortized | O(N) (a rehash, or all keys colliding) | | `remove` | O(1) | O(N) | ] -- | | separate chaining | open addressing | |-|-------------------|-----------------| | where pairs live | in linked lists hanging off the array | in the array itself | | load factor | can exceed 1 | must stay below 1 | | `remove` | unlink a node | needs tombstones | | full-table behavior | slows down gradually | slows down sharply | --- template:section # Other Maps (and Sets) in Java --- ## `TreeMap
`: an Ordered Map - https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/util/TreeMap.html .with-pic[ .text[ - implemented as a __red-black tree__ (a balanced binary search tree), not a hash table, - keys are kept __sorted__: keys must be `Comparable`, or you pass a `Comparator` to the constructor (`TreeMap` uses `compareTo`, not `hashCode` and `equals`), - __guaranteed O(log N)__ for `get`, `put`, `remove`, and `containsKey`: no "average case", no bad worst case, no rehashing. ] .pic[
] ] -- So why not always use it? For `get`/`put`/`remove` alone, `HashMap`'s O(1) beats O(log N). `TreeMap` wins when you need the __order__ of the keys: - iterate over the keys in sorted order, - find the smallest or largest key, - find the key closest to a value that is not in the map, - get all keys in a range. A hash table scatters keys on purpose, so it cannot do any of these without looking at every key. --- ## What a `TreeMap` Can Do Letter grades from score cutoffs: ```java TreeMap
cutoffs = new TreeMap<>(); cutoffs.put(90, "A"); cutoffs.put(80, "B"); cutoffs.put(70, "C"); cutoffs.put(60, "D"); cutoffs.put(0, "F"); System.out.println(cutoffs.floorEntry(87).getValue()); // B (largest key <= 87 is 80) System.out.println(cutoffs.get(87)); // null (87 itself is not a key) ``` -- Some of the methods (from the `NavigableMap` interface), all O(log N): | method | returns | |--------|---------| | `firstKey()`, `lastKey()` | the smallest / largest key | | `floorKey(k)`, `ceilingKey(k)` | the largest key `<= k` / the smallest key `>= k` | | `lowerKey(k)`, `higherKey(k)` | the largest key `< k` / the smallest key `> k` | | `headMap(k)`, `tailMap(k)`, `subMap(a, b)` | a view of the keys `< k`, `>= k`, in `[a, b)` | .smaller[`floorEntry`, `ceilingEntry`, ... do the same but return the whole `(key, value)` pair.] --- ## Choosing a Map | | `HashMap` | `LinkedHashMap` | `TreeMap` | |-|-----------|-----------------|-----------| | built on | hash table | hash table + a linked list through all entries | red-black tree | | `get` / `put` / `remove` | O(1) average | O(1) average | O(log N) guaranteed | | iteration order | no particular order | insertion order (or access order) | sorted by key | | keys need | `hashCode` + `equals` | `hashCode` + `equals` | `compareTo` (or a `Comparator`) | | sorted / range queries | no | no | yes | -- __Rule of thumb:__ use `HashMap` unless you need an order. Then use `LinkedHashMap` for "the order I added them in", or `TreeMap` for "sorted order". --- ## `LinkedHashMap`: a Cache in a Few Lines `LinkedHashMap` can keep entries in __access order__ (most recently used last) and can drop the oldest entry automatically. That is exactly an __LRU (least recently used) cache__: ```java class LRUCache
extends LinkedHashMap
{ private final int capacity; LRUCache(int capacity) { super(16, 0.75f, true); // true = access order instead of insertion order this.capacity = capacity; } @Override protected boolean removeEldestEntry(Map.Entry
eldest) { return size() > capacity; // called after each put: drop the least recently used } } ``` -- - `16` and `0.75f` are the initial capacity and the __load factor__ threshold from the rehashing section, - caches like this are everywhere: web browsers, databases, operating systems. --- ## Sets Are Maps Without Values Each map has a matching set, built on top of it (the set's elements are the map's keys): | set | built on | order | `add` / `contains` / `remove` | |-----|----------|-------|--------------------| | `HashSet
` | `HashMap` | no particular order | O(1) average | | `LinkedHashSet
` | `LinkedHashMap` | insertion order | O(1) average | | `TreeSet
` | `TreeMap` | sorted | O(log N) guaranteed | ```java Set
seen = new HashSet<>(); for (String word : words) { if (!seen.add(word)) // add returns false if word was already there System.out.println("repeated: " + word); } ``` --- ## Other Things Worth Knowing .smaller[ - __Handy `Map` methods__ (Java 8+): - `getOrDefault(key, d)` - the value for `key`, or `d` if there is none, - `merge(key, 1, Integer::sum)` - the whole word-count loop body in one line, - `computeIfAbsent(key, k -> new ArrayList<>()).add(x)` - a map from keys to __lists__ of values, - `for (Map.Entry
e : map.entrySet())` - loop over keys and values together. - __`Map.of("a", 1, "b", 2)`__ (Java 9+) - a small map that cannot be changed. - __`EnumMap`__ - for keys that are an `enum` (e.g. `DayOfWeek`): just an array indexed by the enum's position. This is our "use the key as the index" idea from the beginning of the lecture! - __`ConcurrentHashMap`__ / __`ConcurrentSkipListMap`__ - hash and sorted maps that many threads can use at the same time (you will meet threads in later courses). - __`IdentityHashMap`__ - compares keys with `==` instead of `equals`, uses linear probing. - __`SequencedMap`__ (Java 21+) - an interface for maps with a defined order (`LinkedHashMap`, `TreeMap`): `firstEntry()`, `lastEntry()`, `reversed()`, ... ] --- template:section # Examples and Things to Think About --- ## Do we need the `key`s? Do we actually need to store the keys in a hash table? Which operations could do without keys? For which operations are keys necessary? --- ## Practice 1. Insert the keys `22, 1, 13, 11, 24, 33, 18, 42, 31` (in this order) into a table of size `M = 11` with `hash(key) = key % 11`, using - separate chaining, - linear probing, - quadratic probing. For each, how many collisions occurred? Which keys are not at their home index? -- 2. Java's `HashSet
` is implemented using a `HashMap`. What do you think it uses as keys? As values? -- 3. `String.hashCode()` multiplies by 31. Why do you think 31 was chosen? What would go wrong if the multiplier was 1? What about 2? -- 4. For each task, would you use a `HashMap` or a `TreeMap`? - count how many times each word appears in a book, - print all students in alphabetical order of NetID, - find all events scheduled between 9am and 11am. --- ## Practice: Linear Probing with Removal Table size `M = 7`, `hash(key) = key % 7`, linear probing, and `remove` leaves a `DELETED` marker. 1. Insert the keys `10, 17, 24, 3` (in this order). Draw the table. 2. Run `remove(17)`. Draw the table. 3. Run `get(3)`. Which locations are checked? What is returned? 4. Run `get(17)`. Which locations are checked? Why does the search stop where it does? 5. Run `put(31, ...)`. Where does 31 go? Why can't `put` simply use the first `DELETED` location it finds without looking any further? ??? 1. All four keys hash to 3: 10 at index 3, 17 at 4, 24 at 5, 3 at 6. 2. Index 4 becomes DELETED. 3. Indexes 3, 4 (DELETED, keep going), 5, 6: found, 4 locations. 4. Indexes 3, 4, 5, 6, 0: index 0 is null (never used), so stop: not found, 5 locations. 5. 31 % 7 = 3. put must first make sure 31 is not further along (checks 3, 4, 5, 6, 0 and stops at null), then puts 31 into the first DELETED location it passed: index 4. If 31 were already further along, reusing index 4 right away would create a duplicate key. --- ## Practice: When Does Rehashing Happen? Separate chaining, table size `M = 5`, `hash(key) = key % M`. Before each insertion, if the insertion would make the load factor greater than `0.75`, the table grows to size `2M + 1` first. 1. Insert the keys `3, 8, 13, 6` (in this order). - What does the table look like after the first three insertions? - Does inserting `6` cause a rehash? What is the new size? - Draw the table after all four insertions. 2. How many key comparisons does `get(13)` make before the rehash? After? ??? 1. 3, 8, 13 all hash to 3: one chain at index 3: 3 -> 8 -> 13. Load factor 3/5 = 0.6. Inserting 6 would make it 4/5 = 0.8 > 0.75, so rehash first to size 11. After rehashing: 3 at index 3, 8 at index 8, 13 at index 2; then 6 at index 6. No collisions at all in the new table. 2. Before: 3 comparisons (3, 8, 13). After: 1. --- ## Practice: Is This `hashCode()` OK? ```java class Student { private int id; private String name; @Override public boolean equals(Object o) { // two students are equal if their ids are equal if (!(o instanceof Student)) return false; return id == ((Student) o).id; } } ``` For each possible `hashCode()`: does it follow the contract? Is it a __good__ hash function? 1. `return Objects.hash(id);` 2. `return Objects.hash(id, name);` 3. `return 42;` 4. `return id % 10;` 5. `return (int) (Math.random() * 1000);` ??? 1. Correct and good. 2. Breaks the contract: two students with the same id but different names are equal but have different hash codes. 3. Follows the contract (equal objects get equal hash codes) but is terrible: every key collides, O(N) operations. 4. Follows the contract, but only 10 possible hash codes: many collisions. 5. Breaks the contract (not repeatable): the same object gets a different hash code every time, so get will almost never find it. --- ## Practice: Colliding Strings `String.hashCode()` computes `s[0]*31^(n-1) + s[1]*31^(n-2) + ... + s[n-1]`. 1. Compute `"Aa".hashCode()` and `"BB".hashCode()` by hand (`'A'` is 65, `'B'` is 66, `'a'` is 97). 2. Does that mean `"Aa".equals("BB")`? Does it break the `hashCode()`/`equals()` contract? 3. Using these two strings, find four different strings of length 4 that all have the same hash code. How many strings of length 20 could you build this way? 4. Why is this a problem for a web server that stores form field names in a `HashMap`? ??? 1. "Aa": 65 * 31 + 97 = 2112. "BB": 66 * 31 + 66 = 2112. 2. No, they are not equal, and it does not break the contract: unequal objects may share a hash code (a collision). 3. "AaAa", "AaBB", "BBAa", "BBBB" all have hash code 2031744. Length 20 = 10 blocks, each "Aa" or "BB": 2^10 = 1024 strings with the same hash code. 4. Hash flooding: an attacker sends many keys that all collide, and every operation becomes slow (in Java 8+, O(log N) per operation thanks to treeified chains, instead of O(N)). --- ## Practice: Quick Questions 1. A `HashMap` (default settings: starting capacity 16, load factor 0.75, capacity doubles when needed) holds 1000 entries. How big is its array? 2. You put the `Integer` keys `0, 1, 2, ..., 999` into a `HashMap` whose array has 1024 locations. How many collisions are there? 3. You print the keys of a `HashMap`, add one more key, and print them again. The order of the keys changed. Why? 4. What does `map.put(key, value)` return, and how can you use that to tell whether `key` was new? 5. Which data structure would you use for each, and why? - a spell checker that needs to tell whether a word is in the dictionary, - a leaderboard that always shows the top 10 scores, - the "recently viewed items" list on a shopping site (keep the last 20). ??? 1. 2048: with 1024 locations the threshold is 1024 * 0.75 = 768 < 1000, so it doubles to 2048 (threshold 1536). 2. None: Integer.hashCode() is the value itself, and for values below 65536, (h ^ (h >>> 16)) & 1023 is just h. 3. Adding the key pushed the map over its threshold, so it rehashed: every key got a new index. 4. The previous value for key, or null if there was none (careful: also null if the old value was null). 5. HashSet
; TreeMap (or TreeSet), sorted by score; LinkedHashMap with removeEldestEntry (the LRU cache slide).