Search code examples
flutterdartsetcomparison

How does Dart Set<E> compare items?


I just stuffed a bunch of MyClass inside a Set in Dart. MyClass does not implement Comparable, and does not have an == operator defined. It compiled fine.

For this Set to detect duplicates properly, do I have to implement Comparable interface, or just override the == operator?


Solution

  • 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 == and hashCode in your custom class. Set's default implementation is a LinkedHashSet, which does not use Comparable. (There is a SplayTreeSet implementation that does use Comparable, however, but lookup and insertions would be O(log n) instead of O(1).)
    • Alternatively use the LinkedHashSet constructor or the HashSet constructor and pass appropriate callbacks for equality and hash code computations.