Explore how hash tables are specialized into fundamental building blocks across production Android and distributed systems.
1. Sets: Mathematical Uniqueness via Hash Keys
A Set is an Abstract Data Type that stores unique elements with zero duplicates.
How is HashSet implemented under the hood?
A HashSet is simply a HashMap where values are dummy placeholder objects!
// Conceptual implementation of HashSet
class MyHashSet<E> {
private val PRESENT = Any() // Shared dummy value
private val map = HashMap<E, Any>()
fun add(element: E): Boolean = map.put(element, PRESENT) == null
fun contains(element: E): Boolean = map.containsKey(element)
fun remove(element: E): Boolean = map.remove(element) != null
}
Every set operation (add, remove, contains) runs in O(1) time by delegating directly to hash table keys.
2. Android Memory Optimization: SparseArray
In standard Java/Kotlin:
val map = HashMap<Int, String>()
Because Java generics require objects, every primitive int key must be autoboxed into an Integer object:
Integeroverhead: 16-byte object header + 4-byte payload = 24 bytes per key!- Plus
Map.Entrynode overhead: 32 bytes!
Android's Solution: SparseArray
Android provides custom memory-optimized collections in the platform SDK:
SparseArray<E>(maps primitiveint→Object)SparseIntArray(maps primitiveint→int)LongSparseArray<E>(maps primitivelong→Object)
SparseArray Internal Structure (No autoboxing, no linked nodes!):
mKeys: [ 10, 25, 40, 99 ] (Contiguous primitive IntArray)
mValues: [ obj1, obj2, obj3, obj4 ] (Contiguous Array of Object pointers)
SparseArray trades O(1) hashing for O(log n) binary search across contiguous arrays, saving hundreds of kilobytes of RAM on mobile devices.
3. Distributed In-Memory Caches (Redis & Memcached)
At server scale, Redis is essentially a massive, thread-safe, network-accessible Hash Table:
- Stores billions of key-value pairs in RAM.
- Employs progressive background rehashing to avoid blocking the server while resizing large tables.
Summary
HashSetis implemented directly on top ofHashMapkeys with dummy values.- Android provides
SparseArrayto eliminate the heavy autoboxing overhead ofHashMap<Int, V>. - In-memory key-value databases like Redis are distributed hash tables.