Sorry if this is obvious but I just realized I was...
# getting-started
c
Sorry if this is obvious but I just realized I wasn’t sure — is equality in a
Set
compared via
equals()
?
g
Afaik HashSet/HashMap first check with hashCode() then, if hashCodes are similar, use equals()
👍 1
j
The Java definition of the
Set
interface defines equality using
equals()
, but the Kotlin definition is lousy here (honestly most of Kotlin's stdlib KDoc is really less precise than the Java counterpart, potentially because it could vary across platforms). So technically in Kotlin it depends on the `Set`'s implementation, but it's a pretty safe bet to say that equality should be based on
equals()
in most implementations (at least on the JVM). The most common one (
HashSet
) uses
hashCode()
and then
equals()
to break ties as @Grégory Lureau said.
e
hashCode is required to be consistent with equals (this is documented in both Kotlin https://kotlinlang.org/api/latest/jvm/stdlib/kotlin/-any/hash-code.html and Java https://docs.oracle.com/javase/8/docs/api/java/lang/Object.html#hashCode--) thus hashCode is just an optimization for Set, Map; the collection has the same behavior as if it used just equals
3
c
Thanks everyone!
e
a couple exceptions I just remembered: java.util.IdentityHashMap does break the contract that keys use
equals
, because it uses object identity instead. also SortedSet/SortedMap can be inconsistent with equals depending on the implementation of Comparable.compareTo or Comparator.compare. but the point stands that sets and map keys are generally expected to compare by equals
💯 1
j
TIL there is an
IdentityHashMap
, thanks!