The hashCode() function

In mathematics, a set is a collection of unique values that does not allow duplicates. The hashCode is a function that generates a unique number for each input. 

Let's take a look at the importance of the hashCode function:

  1. Create three objects of a Person class, two with the same values and one with a different value:
class Person(var name : String, var age: Int, var height: Double)
val p1 = Person("Abid", 40, 6.0)
val p2 = Person("Abid", 40, 6.0)
val p3 = Person("Khan", 40, 6.0)

  1. Create a hash set of the Person class and add all three objects in it:
val set = hashSetOf(p1,p2,p3) 
  1. Check the size of this collection. The set must remove the duplicates and keep only unique elements. In this case, the size of this set should be two.

Take a look at a complete code example and verify the output:

class Person(var name : String, var age: Int, var height: Double)
fun main(args: Array<String>) {

val p1 = Person("Abid", 40, 6.0)
val p2 = Person("Abid", 40, 6.0)
val p3 = Person("Khan", 40, 6.0)

val set = hashSetOf(p1,p2,p3)
println("Set contains ${set.size} elements")

val result = set.contains(Person("Abid",40,6.0))
println("Search result = $result")
}

When we execute the code, the output window does not show the expected result:

Although the first two instances are exactly the same, the output is Set contains 3 elements. This situation becomes more interesting when we see that set.contains couldn't find a person with the same properties. The reason behind this behavior is that the Person class has not implemented the hashCode function. The main responsibility of the hashCode function is to generate a distinct number for each object. If the properties of two objects contain the same values, the hash code of these objects is the same. The good news is that we do not need to implement this function, because the data class already implemented it for us. Turn the normal class into a data class and execute this code again:

data class Person(var name : String, var age: Int, var height: Double)

This time, the output is different; the set has 2 elements and the set.contain function successfully found the object of the specified values:

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.137.223.10