Assume we have three sets of strings in Scala. One has elements A,B,C. Two has elements B,C,D. And Three has elements J,K,I.
My first question is, is there any way that the hashcodes for any two of these sets could be the same? My second question is, if I add D to One and A to Two to get new Sets One.n and Two.n, are the hashcodes for One.n and Two.n the same?
Question 1) In general yes, entirely possible. A hashcode is a limited number of bytes long. A Set can be any size. So hashcodes cannot be unique (although usually they are).
Question 2) Why not try it?
scala> val One = collection.mutable.Set[String]("A", "B", "C")
One: scala.collection.mutable.Set[String] = Set(A, B, C)
scala> One.hashCode
res3: Int = 1491157345
scala> val Two = collection.mutable.Set[String]("B", "C", "D")
Two: scala.collection.mutable.Set[String] = Set(B, D, C)
scala> Two.hashCode
res4: Int = -967442916
scala> One += "D"
res5: One.type = Set(A, B, D, C)
scala> Two += "A"
res6: Two.type = Set(B, D, A, C)
scala> One.hashCode
res7: Int = -232075924
scala> Two.hashCode
res8: Int = -232075924
So, yes they are, as you might expect, since you would expect the == method to be true for these two instances.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With