The Analogy: The Lost Property Office and the Pigeonholes
Behind the parcels counter at a big terminus is a room lined floor to ceiling with pigeonholes, and everything left on a train ends up in it. A porter brings in an umbrella; the clerk writes a line in the day book -- ticket 41, black umbrella, eight ribs, off the 6.40 -- ties a numbered card to the handle and puts it in a hole. The office holds four thousand articles, and the clerk who files one is almost never the clerk who hands it back.
Two different questions get asked at that counter. A claimant says "I left a black umbrella with eight ribs on the 6.40" -- a question about description: does anything here match those particulars? A porter says "the umbrella I brought in had a name tape sewn inside, has it gone out yet?" -- a question about one specific article, not one like it but that one, ticket 41, the object itself. The first can truthfully be answered "three of them". The second has exactly one answer, and no amount of matching particulars will produce it.
Nobody searches four thousand pigeonholes. The office files by description: the kind of article and its colour together decide which hole it goes in, so every black umbrella is in one hole and every brown glove in another. That gives the office a rule it can never break. If two articles match on description they must be in the same hole, or a clerk searching the hole the description names will fail to find an article sitting in the room. The rule does not run the other way -- a black umbrella and a black cane may share a hole -- so having found it, the clerk still reads every card in it.
Two things go wrong in that room, and both go wrong quietly. The first is an article altered after filing. A porter finds the name tape and writes "black umbrella, initials J.R." on the card; the article now describes something that belongs in a different hole and is still lying in the old one. It is in the office, on the shelf, and nobody will ever find it, because every search that could reach it now looks elsewhere and not one line of the day book is wrong. The second is a clerk answering the description question when the claimant asked the identity one. Three umbrellas match, so the clerk hands over the nearest, the book balances, and the man who handed in ticket 41 walks off with ticket 47.
Syntax or Core Structure
Kotlin asks the two questions with two operators. == asks the description question, and despite looking like a pointer comparison it is not one: the compiler rewrites a == b into a null-safe call to a.equals(b), which is why it never throws on a null left operand. === asks the identity question and compares nothing but the two references. The equals inherited from Any compares references, so a class that does not override it answers both questions alike.
class Umbrella(val maker: String, val ribs: Int) {
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Umbrella) return false
return maker == other.maker && ribs == other.ribs
}
override fun hashCode(): Int = maker.hashCode() * 31 + ribs
override fun toString(): String = maker + "/" + ribs
}
fun main() {
val a = Umbrella("Fox", 8)
val b = Umbrella("Fox", 8)
val c = a
println("a describes " + a + " and b describes " + b)
println("a == b: " + (a == b) + " a === b: " + (a === b))
println("a == c: " + (a == c) + " a === c: " + (a === c))
println("a != b: " + (a != b) + " a !== b: " + (a !== b))
println("hashes equal: " + (a.hashCode() == b.hashCode()))
val ticket: Umbrella? = null
println("ticket == a: " + (ticket == a) + " ticket === null: " + (ticket === null))
val shelf = setOf(a, b, c)
println("shelf holds " + shelf.size + " umbrella")
}
Output:
a describes Fox/8 and b describes Fox/8
a == b: true a === b: false
a == c: true a === c: true
a != b: false a !== b: true
hashes equal: true
ticket == a: false ticket === null: true
shelf holds 1 umbrella
Read the second and third lines together; between them they are the whole topic. a and b came from two separate constructor calls, so they are two objects carrying identical particulars: the description question says yes, the identity question says no. c was never constructed at all -- val c = a copied a reference, so c and a are one object under two names and both questions say yes. Nothing will ever make === true for a and b, or false for a and c.
The last two lines are the consequences. ticket == a is a call on a null receiver and does not throw, because the compiler emitted the null check; a hand-written ticket.equals(a) would not compile without a safe call, and ticket!!.equals(a) would throw. setOf(a, b, c) was handed three references and reports a size of one, because a set decides membership with hashCode and then equals, and by those answers all three are the same umbrella. Without the overrides it would report two.
Technical Depth: Two Questions and One Contract
Every comparison you can write falls on one side of that divide, and the two operators are one character apart.
| Written | The question it asks | What it actually runs |
|---|---|---|
a == b | do these describe the same thing | a?.equals(b) ?: (b === null) |
a === b | are these one object | a reference comparison, no method call |
a != b and a !== b | the same two questions, negated | the same machinery, result inverted |
a.equals(b) | the description question without the guard | equals directly, so a null a throws |
xs.contentEquals(ys) | do these arrays hold equal elements in order | equals on each element in turn |
Overriding equals is not a free choice made in isolation. It is a promise to every hash-based collection in the standard library: equal objects must hash alike, equals must stay reflexive, symmetric and transitive, and the fields it reads must not change while the object is a key. Break any of those and nothing throws -- contains, indexOf and distinct simply begin returning answers that depend on argument order or on when you asked.
The comparisons that disagree with themselves
Two families of type answer == and equals differently: floating point, where the two spellings select either IEEE 754 or the total order, and arrays, which never override equals at all.
fun main() {
val nanA = Double.NaN
val nanB = 0.0 / 0.0
println("NaN == NaN: " + (nanA == nanB))
println("NaN.equals(NaN): " + nanA.equals(nanB))
val zero = 0.0
val negZero = -0.0
println("0.0 == -0.0: " + (zero == negZero))
println("0.0 equals -0.0: " + zero.equals(negZero))
println("1.0 divided by each: " + (1.0 / zero) + " and " + (1.0 / negZero))
val readings = listOf(nanA, zero, negZero)
println("list contains NaN: " + readings.contains(nanB))
println("list indexOf -0.0: " + readings.indexOf(negZero))
val left = intArrayOf(1, 2, 3)
val right = intArrayOf(1, 2, 3)
val asAny: Any = left
println("arrays via equals: " + (asAny == right) +
" contentEquals: " + left.contentEquals(right))
println("array sizes " + left.size + " and " + right.size +
" sums " + left.sum() + " and " + right.sum())
}
Output:
NaN == NaN: false
NaN.equals(NaN): true
0.0 == -0.0: true
0.0 equals -0.0: false
1.0 divided by each: Infinity and -Infinity
list contains NaN: true
list indexOf -0.0: 2
arrays via equals: false contentEquals: true
array sizes 3 and 3 sums 6 and 6
Lines one and two compare the same two values through the same class and disagree, and so do lines three and four. The rule is mechanical: where the compiler can see statically that both operands are Double or Float it emits IEEE 754, and everywhere else -- an explicit equals, or any context that boxes the value -- the total order applies. IEEE requires NaN to compare unequal to itself, because NaN means "no answer" and two missing answers are not the same answer; a collection has to be able to find what you put into it, so the total order makes every value equal to itself. Line five is why the two zeros must stay distinguishable: they are equal under == and not interchangeable.
Lines six and seven show which definition wins inside a collection. readings is a List<Double>, so its elements are boxed and contains runs equals, which finds the NaN that == said was not there. indexOf(negZero) returns 2, not 1, walking past the positive zero at index 1 that == would have accepted. The last two lines are the array trap: two arrays of the same size holding the same numbers with the same sum, and the description question answers false, because the only equals an array has is the reference comparison it inherited.
What a data class generates, and what it leaves out
A data class builds equals, hashCode, toString, copy and the component functions from the primary constructor's properties and nothing else. A property declared in the class body is invisible to all of them.
data class Article(val ticket: Int, val description: String) {
var shelf: String = "unsorted"
}
class Parcel(var ticket: Int, val description: String) {
override fun equals(other: Any?): Boolean = other is Parcel && ticket == other.ticket
override fun hashCode(): Int = ticket
override fun toString(): String = ticket.toString() + ":" + description
}
fun main() {
val one = Article(11, "black umbrella")
val two = Article(11, "black umbrella")
two.shelf = "B4"
println("shelves " + one.shelf + " and " + two.shelf + " but equal: " + (one == two))
println("same hash: " + (one.hashCode() == two.hashCode()))
val p = Parcel(12, "walking cane")
val q = Parcel(12, "fishing rod")
println("parcels " + p + " and " + q + " equal: " + (p == q) +
" hash " + p.hashCode() + " and " + q.hashCode())
val office = hashSetOf(p)
println("filed under " + p.hashCode() + ", found: " + office.contains(p))
p.ticket = 99
println("renumbered to " + p.hashCode() + ", found: " + office.contains(p))
println("office size still " + office.size + " and iteration finds " + office.first())
}
Output:
shelves unsorted and B4 but equal: true
same hash: true
parcels 12:walking cane and 12:fishing rod equal: true hash 12 and 12
filed under 12, found: true
renumbered to 99, found: false
office size still 1 and iteration finds 99:walking cane
The first two lines are the data class keeping a promise you may not have realised you made. one and two are shelved in different places and are still equal, because shelf was declared in the body and the generated equals cannot see it. copy shares the blind spot, initialising every body property from scratch rather than carrying it across. If two objects differing in a body property must compare unequal, that property belongs inside the parentheses.
The last four lines are the mutable key. Parcel keys equality on the ticket alone, which is the pigeonhole rule working as intended, since two parcels bearing one ticket are one claim. Then p.ticket = 99 changes the value hashCode is computed from while p sits inside a HashSet. The set filed it under 12 and it is still in that bucket; contains now hashes 99, looks in the bucket that number names, and finds nothing. The set still reports a size of one, and an iteration still hands the parcel straight back: the element is present and unreachable at once. That false is what this JVM's HashSet happens to do, not something the language guarantees -- the contract says only that a set's behaviour is unspecified once a member's equality fields change.
Real World Example: The Terminus Lost Property Board
The board below is the end-of-day summary such an office would post: one row per description, how many articles carry it, how many survive a shelf that treats matching descriptions as one article, and which ticket a clerk reaches for first. Article keys equals and hashCode on the kind and the colour, not on the ticket.
const val FOUND =
"41:UMBRELLA:BLACK,42:UMBRELLA:BLACK,43:GLOVE:BROWN,44:UMBRELLA:BLUE,45:GLOVE:BROWN,46:CANE:BLACK,47:UMBRELLA:BLACK"
val STATUSES = listOf("UNIQUE", "AMBIG")
const val W_DESC = 16
const val W_FILED = 6
const val W_KEPT = 6
const val W_FIRST = 7
const val W_LOST = 6
const val W_STATUS = 9
class Article(val ticket: Int, val kind: String, val colour: String) {
val description: String get() = kind + "/" + colour
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (other !is Article) return false
return kind == other.kind && colour == other.colour
}
override fun hashCode(): Int = kind.hashCode() * 31 + colour.hashCode()
}
fun row(desc: String, filed: String, kept: String, first: String,
lost: String, status: String): String =
desc.padStart(W_DESC) + filed.padStart(W_FILED) + kept.padStart(W_KEPT) +
first.padStart(W_FIRST) + lost.padStart(W_LOST) + status.padStart(W_STATUS)
fun main() {
val width = W_DESC + W_FILED + W_KEPT + W_FIRST + W_LOST + W_STATUS
val articles = FOUND.split(",").map { entry ->
val part = entry.split(":")
Article(part[0].toInt(), part[1], part[2])
}
val order = mutableListOf<String>()
for (a in articles) if (!order.contains(a.description)) order.add(a.description)
val tally = IntArray(STATUSES.size)
val counts = mutableListOf<Int>()
var tFiled = 0
var tKept = 0
var tLost = 0
println(row("DESCRIPTION", "FILED", "KEPT", "FIRST", "LOST", "STATUS"))
println("-".repeat(width))
for (desc in order) {
val group = articles.filter { it.description == desc }
val shelf = HashSet<Article>()
for (a in group) shelf.add(a)
val filed = group.size
val kept = shelf.size
val lost = filed - kept
val status = if (filed == 1) "UNIQUE" else "AMBIG"
tally[STATUSES.indexOf(status)]++
tFiled += filed
tKept += kept
tLost += lost
counts.add(filed)
println(row(desc, filed.toString(), kept.toString(),
group[0].ticket.toString(), lost.toString(), status))
}
println("-".repeat(width))
println(row("TOTALS", tFiled.toString(), tKept.toString(), "--",
tLost.toString(), order.size.toString() + " DESCS"))
println("status: " + STATUSES.indices.joinToString(" ") { STATUSES[it] + "=" + tally[it] })
println("filed " + tFiled + " = kept " + tKept + " + lost " + tLost +
" agree: " + (tKept + tLost == tFiled))
var sum = 0
for (c in counts) sum += c
println("by description: " +
order.indices.joinToString(" ") { order[it] + "=" + counts[it] } +
" sum " + sum + " agree: " + (sum == tFiled))
val wanted = Article(0, "UMBRELLA", "BLACK")
val handedIn = articles.last()
val given = articles[articles.indexOfFirst { it == wanted }]
println("claim " + wanted.description + " on ticket " + wanted.ticket + " matches " +
articles.count { it == wanted } + " articles, clerk gives ticket " + given.ticket)
println("claimant handed in ticket " + handedIn.ticket +
" same article: " + (given === handedIn) + " equal: " + (given == handedIn))
}
Output:
DESCRIPTION FILED KEPT FIRST LOST STATUS
--------------------------------------------------
UMBRELLA/BLACK 3 1 41 2 AMBIG
GLOVE/BROWN 2 1 43 1 AMBIG
UMBRELLA/BLUE 1 1 44 0 UNIQUE
CANE/BLACK 1 1 46 0 UNIQUE
--------------------------------------------------
TOTALS 7 4 -- 3 4 DESCS
status: UNIQUE=2 AMBIG=2
filed 7 = kept 4 + lost 3 agree: true
by description: UMBRELLA/BLACK=3 GLOVE/BROWN=2 UMBRELLA/BLUE=1 CANE/BLACK=1 sum 7 agree: true
claim UMBRELLA/BLACK on ticket 0 matches 3 articles, clerk gives ticket 41
claimant handed in ticket 47 same article: false equal: true
Read the board a column at a time. FILED counts the articles carrying each description, and 3 + 2 + 1 + 1 is the 7 in the totals row. KEPT asks a HashSet how many of them it considers distinct, and every row answers one, because within a group the descriptions match by construction. LOST is the difference, FIRST is the ticket a clerk searching in order would reach, and 7 minus 4 gives the 3 that both audit lines confirm.
The last two lines are the counter, and they are why the topic matters. wanted is constructed with ticket 0, a number no article carries, and it matches three of them, because equals reads the kind and the colour and nothing else: a claimant's description is a perfectly good Article as far as this class is concerned. indexOfFirst returns the earliest match, so the clerk reaches for ticket 41. Then the last line asks both questions about that one handover -- given == handedIn is true, given === handedIn is false. The umbrella being held out matches the claimant's in every recorded particular and is not the claimant's.
Several details exist only to keep the output fixed. The row order comes from order, a list built by first appearance, because iterating the HashSet would order rows by hash code. The status line is driven by the declared STATUSES list, so UNIQUE always precedes AMBIG. The six width constants sum to 50, so every row is exactly 50 characters and both rules are 50 dashes: FILED begins at index 16, KEPT at 22, FIRST at 28, LOST at 35 and STATUS at 41.
The flaw is not in the board, it is in the two lines below it. filed 7 = kept 4 + lost 3 agree: true cannot fail: lost is computed as filed - kept, so the identity being checked is kept + (filed - kept) == filed, which would print true if the shelves had swallowed all seven articles. The by description line is the same trick, since counts holds group.size -- the very numbers FILED was printed from -- so summing them validates the grouping and never touches the filing. Nothing on this board can come out false, and two confident-looking reconciliation lines are exactly what makes a reader stop checking. The honest check is the one the program never makes: articles parsed out of FOUND against articles the shelves can still produce, 7 against 4. Two narrower limits: because equals ignores the ticket, identity can only be asked with ===, which is useless at a counter where the claimant has a description and not a reference; and padStart never truncates, so the first description over sixteen characters shifts every column on its row and the board stops being a table.
Common Mistakes
- Reaching for
===when you mean==. In Java,==between objects is the reference comparison. Kotlin swaps the spelling:==is structural and===is referential. A Java habit maps straight onto the wrong operator, and the wrong operator compiles cleanly and is right by accident on the first few objects you test.
- Overriding
equalswithouthashCode. Two objects thatequalscalls equal but that hash differently land in different buckets, so aHashSetholds both of them,containsreports false for an element sitting in the collection, and a map lookup with a freshly built key returns null. Nothing throws.
- Letting a mutable field into
equalsandhashCode. Avarin the primary constructor of a data class is enough. The moment that field changes, the object is filed under a hash code it no longer reports, and it becomes present in the collection and unreachable from it at once.
- Assuming a data class compares its body properties. The generated
equals,hashCode,toString,copyandcomponentNare built from the primary constructor and nothing else, andcopyresets a body property to its initialiser rather than carrying it across.
- Comparing arrays with
==. Arrays inheritequalsfromAnyand never override it, so the structural question quietly becomes a reference comparison and answers false for two arrays holding identical elements.contentEqualsis the comparison you wanted, andcontentDeepEqualsfor arrays of arrays.
- Trusting
==onDoubleandFloat. With both operands statically floating point the compiler emits IEEE 754, in which NaN is unequal to itself and-0.0 == 0.0is true. Box the same values or callequalsand both answers invert. Compare with an explicit tolerance, and never use a floating-point value as a map key.
- Writing
other is Tin anopenclass. A subclass instance passes theischeck, so a comparison of a parent against a child can be true while the same comparison written the other way round is false. Symmetry is gone, andcontainsanddistinctstart depending on which side each argument landed on. ComparejavaClassinstead, or keep the class final.
- Assuming
compareToagrees withequals.TreeSetandTreeMapdecide membership by comparing, not by callingequals, so two objects a comparator sorts to the same place count as one element there and two in aHashSet. MakecompareToreturn zero on exactly the pairsequalsaccepts.
- Testing reference identity on strings or boxed numbers.
===between two strings with the same content, or between two boxedIntvalues, may be true or false depending on literal interning and the JVM's cache of small integers. The answer is implementation-dependent, and no program should branch on it.
Best Practices
- Use
==by default and write===only where identity is genuinely the question, with a comment naming the object you mean.
- Let the compiler generate equality where you can: a
data classor avalue classgets the whole contract right, and hand-writtenequalsis where symmetry and null handling go wrong.
- Keep every property that
equalsreads immutable, and immutable all the way down, for anything used as a map key or a set element.
- Override
equalsandhashCodein one edit from one written-down list of fields, and derive the hash from that list rather than a formula that drifts away from it later.
- Open a hand-written
equalswithif (this === other) return true: it is a fast path, and it makes reflexivity impossible to get wrong.
- Never key equality on a floating-point field. Scale the value to an integer and compare that, or compare with a tolerance somewhere that is not
equals.
- Reach for
contentEqualsthe instant two arrays are compared, and ask whether aListwould serve better, since lists do compare structurally.
- Test the contract rather than assuming it: assert symmetry in both directions, assert that equal objects hash alike, and assert that an object put into a
HashSetis still found after every mutation the surrounding code performs on it.
Practice Exercises
- Write a
Coinclass holding a year and a mint mark, withequalsandhashCodewritten by hand, then put two coins with identical particulars into aHashSetand print the size. Now comment out thehashCodeoverride and print the size again. Explain both numbers, and say which run violates the contract and which merely reveals it.
- Make the
Parcellookup survive. Change the ticket to aval, add a second field that the equality does not read and that is free to change, and prove with printed output that mutating it leavescontainsworking, while a freshly constructed parcel carrying the same ticket is still found in the set.
- Build a list holding NaN, positive zero and negative zero, and print for each of the nine ordered pairs the result of
==, ofequalsand ofcompareTo. Find the pairs where the three answers disagree, and write one sentence for each saying which definition of equality that spelling used.
- Add the honest check to the lost property board: articles parsed out of
FOUNDagainst articles the shelves can still produce, printed with anagree:verdict, and confirm that it prints false. Then rebuildArticlewith equality keyed on the ticket and matching done through a separate description value, and show the board printing 7 kept and 0 lost while the claim line still reports three matching articles.