How Hash Sets Work — API Cheat Sheet
No exercise here — add/contains/remove across Java, C#, Python, and JavaScript/TypeScript, for the "have I seen this before" pattern that shows up everywhere.
This is a reference page, not a graded exercise. A set is a hash map that only stores keys, no values — reach for it whenever a problem is really asking "is this a duplicate" or "have I visited this before," which is a very common pattern.
Java — HashSet<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new HashSet<>() | Set<Integer> s = new HashSet<>(); |
| Add | .add(v) | returns false if it was already present |
| Check membership | .contains(v) | s.contains(5) |
| Remove | .remove(v) | |
| Size | .size() | |
| Iterate | for-each | for (int x : s) — no guaranteed order |
| Build from a collection | new HashSet<>(list) | instant de-duplication |
C# — HashSet<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new HashSet<T>() | var s = new HashSet<int>(); |
| Add | .Add(v) | returns false if it was already present |
| Check membership | .Contains(v) | s.Contains(5) |
| Remove | .Remove(v) | |
| Size | .Count | property, no parens |
| Set operations | .UnionWith(other), .IntersectWith(other), .ExceptWith(other) | mutate s in place |
Python — set
| Want to... | Method | Example |
|---|---|---|
| Create | set() | not {} — that's an empty dict |
| Create with values | set literal | s = {1, 2, 3} |
| Add | .add(v) | |
| Check membership | in | 5 in s |
| Remove | .remove(v) (raises if missing) / .discard(v) (silent) | prefer .discard if you're not sure it's there |
| Size | len(s) | builtin |
| Set operations | s1 | s2 (union), s1 & s2 (intersection), s1 - s2 (difference) | operators, not just methods |
| Build from a list | set(my_list) | instant de-duplication |
JavaScript / TypeScript — Set<T>
| Want to... | Method | Example |
|---|---|---|
| Create | new Set() | const s = new Set<number>(); |
| Add | .add(v) | |
| Check membership | .has(v) | s.has(5) |
| Remove | .delete(v) | |
| Size | .size | property, no parens |
| Iterate | for (const x of s) | preserves insertion order |
| Build from an array | new Set(arr) | instant de-duplication |
| Back to an array | [...s] or Array.from(s) |
The gotcha that costs the most time: Python's {} is an empty dict, not an empty set — you must write set() explicitly. And across every language, sets compare objects/structs by reference unless you're using primitives or the language's built-in value types (strings, numbers) — putting two "equal-looking" custom objects into a set won't dedupe them unless you've defined equality/hashing for that type.
Hints
Companies
No companies reported yet.
Discussion
Sign in to join the discussion.
Loading discussion...
Test results
This question doesn't have a code exercise.