-2

As you know, in Scala ## can be used to get a hash code of something in a null safe way:

scala> def hello : String = "hello"
hello: String

scala> hello.##
res1: Int = 3329

scala> class Cat{}
defined class Cat

scala> val c = new Cat
c: Cat = Cat@3a91d146

scala> c.##
res2: Int = 982634822

My question is when we want to get these hash codes? Is it only used for equality checks or does have any other purpose(s) beyond equality checks?

o-0
  • 1,713
  • 14
  • 29

1 Answers1

1

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!

Florian Baierl
  • 2,378
  • 3
  • 25
  • 50
  • You mean hash code and not hash tag? Also more explanation on this please "but if two objects share the same hash-tag, that does NOT make them automatically equal. IF they are equal, they MUST have the same hash-tag" – o-0 Sep 20 '18 at 07:28
  • Yes, sure. Edited. Maybe you should read up on hash functions in general. A hash function is any function that can be used to map data of arbitrary size to data of a fixed size (Wikipedia). These are used in e.g. `HashMap`s to browse them more efficiently. If searching for an elemnent `x` in a hash map `xmap`, instead of browsing through all of the objects and checking for equality, first a hashfunction is called on x to generate a hashcode. Then we can directly search in the "bucket" in `xmap`that includes all elements with the same hashcode, which makes the search more efficient. – Florian Baierl Sep 20 '18 at 07:38