I think this is quite similar to JAVA where the hashcode needs to be given in order to check for equality for collection items where the unicity of elements is calculated according to the equals()
and the hashCode()
method. E.g. for objects in a HashMap.
This is documented here: java.lang.Object
It is also written like that in "Programming in Scala" by Martin Odersky where he shows that:
val p1, p2 = new Point(1,2)
collection.mutable.HashSet(p1) contains p2
// MAY return false
This may return false because the hashCode
method for Point was not given, but the outcome is not 100% certain. Reason: the contains
method first tries to determine the hash bucket to look in and then compares the given elements with all elements in that bucket.
*Edit: You said that: "I know that we can check for equality of two objects using their hash code, but is that the only reason?" but if two objects share the same hashcode, that does NOT make them automatically equal. IF they are equal, they MUST have the same hashcode, but objects that are unequal MAY have the same hashtag as well.
"hash code is used similar to the pointer in C" ->
No, hashcode are not unique!