liveBook · Manning

Hashset

As explained in Kotlin in Action, 2E

HashSet is a set implementation that organizes elements using hash codes for efficient membership testing.

A HashSet organizes elements by hash codes so membership checks can compare hashes before comparing values. For objects with custom equality, equals and hashCode must agree: equal objects must produce the same hash code. section 4.3.1

Equal customers in a HashSet

val processed = hashSetOf(Customer("Alice", 342562)) println(processed.contains(Customer("Alice", 342562))) // false If Customer overrides equals but not hashCode, the two equal-looking instances can have different hashes, so the set rejects the second instance. An implementation such as `override fun hashCode(): Int = name.hashCode() * 31 + postalCode` restores the contract. section 4.3.1

Kotlin provides several ways to create set implementations:

  • `java.util.HashSet` is represented from Kotlin as a MutableSet-compatible Java collection, without wrappers or copied data. section 8.2.3

How Kotlin in Action, 2E covers it

How deep it goes
Explains hash-first comparison and the equals/hashCode contract, then stops short of implementation internals beyond a hashCode example.
Examples
Uses two equal-looking Customer instances named Alice and compares Kotlin hashSetOf with java.util.HashSet interoperability.
What it assumes
Assumes basic Kotlin classes and equality comparisons while teaching the hashCode contract through a Customer example.
What you can do after
Diagnose membership failures by checking whether equal objects return the same hash code.
How it connects
Connects HashSet with equals, hashCode, Kotlin collections, MutableSet, and Java collections.

Also explained in

Compare how 2 books explain hashset →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Kotlin in Action, 2E. The section links point to the parts of the book it draws on.