CodeBlanks Logo Icon CodeBlanks

equals and hashCode

Learn automatic equals and hashCode generation.

Automatic equals generation

Data classes generate the equals method based on the primary constructor parameters. Two instances are equal if they have the same class and the same property values.

Example: data class Point(val x: Int, val y: Int). Point(1, 2) == Point(1, 2) returns true. In normal classes the == operator does reference comparison, but in data classes it does content comparison. You do not need to write equals yourself.

Automatic hashCode generation

Data classes also generate the hashCode method based on the primary constructor parameters. Equal instances have equal hash codes; this ensures consistent behavior in HashSet and HashMap.

Example: Point(1, 2).hashCode() == Point(1, 2).hashCode() returns true. If equals is true, hashCode must be the same; data classes provide this contract automatically. You do not need to write hashCode by hand.

Practice Equals check with the Point data class

Define a data class named Point with a primary constructor taking val x: Int, val y: Int. In main create two Point(1, 2) instances (a and b). First print the result of a == b, then print the result of a.equals(b) with println.

Starter code

Main.kt
// Define the Point data class
// with x and y properties
// create two instances in main
// print == and equals results

Sample solution

Main.kt
data class Point(val x: Int, val y: Int)

fun main() {
    val a = Point(1, 2)
    val b = Point(1, 2)
    println(a == b)
    println(a.equals(b))
}

Expected output

true
true

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Two <code>Point(1, 2)</code> instances are compared with <code>==</code>. If Point is a data class, what is the result?

Main.kt
In data classes == compares content.
  • false (different references)
  • Compile error
  • Runtime error
  • true (same content) Correct answer

Explanation: A data class == compares content; same values give true.

2 Complete the equals comparison

Question
val a = Point(1, 2)
val b = Point(1, 2)
println(a ____ b)
Answer
val a = Point(1, 2)
val b = Point(1, 2)
println(a == b)

Explanation: The == operator calls equals in data classes.

3 Match equals and hashCode concepts

Term Meaning
Point(1,2) == Point(1,2) Content equality
equals true implies hashCode Must be equal
== in a normal class Reference comparison
data class equals Auto-generated

All lessons in Intermediate