algoritmauzmanı
Sign in
TREN
9.4Hashing Applications
Lesson 9.4.3

Built-in hash tables: HashMap and dict

In real programs you rarely write a hash table yourself: Java has HashMap and HashSet, Python has dict and set. But knowing how they work is the only way to use them correctly. In this lesson you match the built-in structures of both languages to what you learned in this part: which collision method they use, when they grow, and which rules make them go quietly wrong when broken.

What you will learn
  • How to insert, read, search and delete with HashMap and dict
  • Which method each structure uses inside and when it grows
  • The rules to follow when you use your own class as a key, and the mutable key trap
6 min

1Basic operations

In both languages a hash table is a dictionary: a value is attached to every key. Writing with the same key a second time does not make a new entry, it updates the value; this matches the rule in this part that the same key is never inserted twice. The versions that keep keys only are sets: HashSet in Java, set in Python.

java.util.HashMap<String, Integer> age = new java.util.HashMap<>();age.put("Ada", 21);                       // insert or updateage.put("Can", 19);age.put("Ada", 22);                       // same key: the value changesint a = age.get("Ada");                   // 22Integer d = age.get("Deniz");             // null if missingint c = age.getOrDefault("Deniz", 0);     // default if missingboolean has = age.containsKey("Can");     // trueage.remove("Can");for (String name : age.keySet())          // order not guaranteed    System.out.println(name + " " + age.get(name));
age = {}age["Ada"] = 21                 # insert or updateage["Can"] = 19age["Ada"] = 22                 # same key: the value changesa = age["Ada"]                  # 22# age["Deniz"]                  # KeyError if missingc = age.get("Deniz", 0)         # default if missinghas = "Can" in age              # Truedel age["Can"]for name, value in age.items():  # in insertion order    print(name, value)
OperationJava HashMapPython dictAverage time
Insert or updateput(k, v)d[k] = vO(1)
Readget(k): null if missingd[k]: KeyError if missingO(1)
Read with a defaultgetOrDefault(k, v)d.get(k, v)O(1)
Is it there?containsKey(k)k in dO(1)
Deleteremove(k)del d[k] or d.pop(k)O(1)
Number of entriessize()len(d)O(1)
Iteration orderNot guaranteedInsertion order (since 3.7)O(n)

2What is inside?

Java `HashMap` uses chaining. The number of buckets is a power of two, 16 at the start. The key's hashCode() is mixed and the bucket is found with hash & (buckets - 1), a fast way of taking the remainder by a power of two. The threshold is 0.75; once the number of entries goes past it, the number of buckets doubles and the keys are spread out again. If a chain grows past 8 nodes and the table is large enough, that chain is turned into a red-black tree, so even with badly spread keys the worst case becomes O(log n) instead of O(n).

Python `dict` uses open addressing. Probing is not linear but a pseudo-random sequence that also mixes in the high bits of the hash, which reduces . The table is grown once it is two thirds full. The insertion order is kept in a separate, compact array; that is why iteration follows insertion order. set works on the same idea but keeps no values.

The two approaches match the comparison in this part: Java picked chaining for object references and frequent deletion, Python picked open addressing for memory and the cache. Both keep the load factor low to keep the O(1) average.

3Using your own class as a key

A hash table relies on two questions: what is the key's hash, and are two keys equal? In Java these are the hashCode() and equals() methods, in Python __hash__ and __eq__. There is a single rule: two equal objects must have equal hashes. The opposite is not required; different objects giving the same hash is just a .

class Point {    int x, y;    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;    }     @Override    public int hashCode() {        return 31 * x + y;          // equal points give equal hashes    }}

In Java, if you write equals but not hashCode, two Points you consider equal give different hashes and land in different buckets. A HashSet keeps the same point twice and contains does not find it. In Python, if you define __eq__ but not __hash__, the class becomes unhashable and cannot be a dictionary key; the language blocks this mistake from the start.

4The mutable key trap

If a field that affects the hash changes after the key is in the table, the key stays in its old bucket but a search looks in the bucket of its new hash and does not find it. Java does not prevent this: put a Point in a HashSet, then change its x, and the point is still in the set but contains returns false. Python does not accept mutable built-in types such as lists as keys at all: {[1, 2]: 'a'} raises TypeError: unhashable type: 'list'; an immutable tuple is used as the key instead.

5The situation in C

The C standard library has no hash table. POSIX's hsearch functions keep a single global table and do not support deletion, so C programs usually write their own table or use a library. The chained table you wrote in this part is exactly that.

6Try it

In Java you wrote only equals in a class, not hashCode. What happens if you add two equal objects to a HashSet?

Show the answer

The answer is A. The default hashCode comes from the object's identity; two equal objects most likely land in different buckets and equals is never called. Equal objects must have equal hashes.

In Python {(1, 2): 'a'} works but {[1, 2]: 'a'} fails. Why?

Show the answer

The answer is A. The hash of a mutable key could change after it enters the table and the key would be lost. That is why Python does not accept a list as a key. A list can be used as a value.

With default settings, a Java HashMap starts with 16 buckets. On which insertion does it grow for the first time?

Show the answer

The answer is B. The threshold is 16 × 0.75 = 12. Once the number of entries goes past 12, that is when the 13th entry is inserted, the number of buckets goes up to 32.

Lessons you mark show up in the curriculum. If you are signed in, they are saved to your account too.