How does Dart Set<E> compare items?
321
All Dart classes derive from Object
, which does provide operator ==
and hashCode
. Object
's default implementations check for object identity; an instance of your class will compare equal only to itself.
If you want two different instances to be able to compare equal, then you need to:
- Implement
operator ==
andhashCode
in your custom class.Set
's default implementation is aLinkedHashSet
, which does not useComparable
. (There is aSplayTreeSet
implementation that does useComparable
, however, but lookup and insertions would be O(log n) instead of O(1).) - Alternatively use the
LinkedHashSet
constructor or theHashSet
constructor and pass appropriate callbacks for equality and hash code computations.
Author by
Scorb
Updated on December 22, 2022Comments
-
Scorb over 1 year
I just stuffed a bunch of
MyClass
inside aSet
in Dart.MyClass
does not implementComparable
, and does not have an==
operator defined. It compiled fine.For this
Set
to detect duplicates properly, do I have to implementComparable
interface, or just override the==
operator?