https://kotlinlang.org logo
#getting-started
Title
# getting-started
c

Chris Fillmore

10/04/2021, 2:19 PM
Sorry if this is obvious but I just realized I wasn’t sure — is equality in a
Set
compared via
equals()
?
g

Grégory Lureau

10/04/2021, 2:22 PM
Afaik HashSet/HashMap first check with hashCode() then, if hashCodes are similar, use equals()
👍 1
j

Joffrey

10/04/2021, 3:38 PM
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

ephemient

10/04/2021, 4:10 PM
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

Chris Fillmore

10/04/2021, 4:12 PM
Thanks everyone!
e

ephemient

10/04/2021, 7:23 PM
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

Joffrey

10/04/2021, 7:27 PM
TIL there is an
IdentityHashMap
, thanks!