Use equal objects as a key in Map or Set in Kotlin
This article explores different ways to use equal objects as a key in Map or Set in Kotlin.
The default implementation of equals() and hashCode() functions simply checks for the reference equality. This can be problematic if an object is used as a key for Map or Set, and its class does not override equals and hashcode function.
For instance, user1 and user2 have equal values of each field in the following example, but they are considered as two different objects by the Set.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
class User(private val name: String, private val age: Int) { override fun toString(): String { return "{$name, $age}" } } fun main() { val user1 = User("Brad", 18) val user2 = User("Brad", 18) val user3 = User("Steve", 16) val set: MutableSet<User> = mutableSetOf(user1, user2, user3) println(set) } |
Output:
[{Brad, 18}, {Brad, 18}, {Steve, 16}]
You can make Map or Set treat two separate objects, with the same value, as the same by overriding the equals and hashcode function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
class User(private val name: String, private val age: Int) { override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as User if (name != other.name) return false if (age != other.age) return false return true } override fun hashCode(): Int { var result = name.hashCode() result = 31 * result + age return result } override fun toString(): String { return "{$name, $age}" } } fun main() { val user1 = User("Brad", 18) val user2 = User("Brad", 18) val user3 = User("Steve", 16) val set: MutableSet<User> = mutableSetOf(user1, user2, user3) println(set) } |
Output:
[{Steve, 16}, {Brad, 18}]
Alternatively, you can use a data class that automatically implements the equals() and hashCode().
|
1 2 3 4 5 6 7 8 9 10 |
data class User(private val name: String, private val age: Int) fun main() { val user1 = User("Brad", 18) val user2 = User("Brad", 18) val user3 = User("Steve", 16) val set: MutableSet<User> = mutableSetOf(user1, user2, user3) println(set) } |
Output:
[User(name=Brad, age=18), User(name=Steve, age=16)]
That’s all about using equal objects as a key in Map or Set in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)