Skip to content

Comparable<T> abstract interface

abstract interface class Comparable<T>

Interface used by types that have an intrinsic ordering.

The compareTo operation defines a total ordering of objects, which can be used for ordering and sorting.

The Comparable interface should be used for the natural ordering of a type. If a type can be ordered in more than one way, and none of them is the obvious natural ordering, then it might be better not to use the Comparable interface, and to provide separate Comparators instead.

It is recommended that the order of a Comparable agrees with its operator operator == equality (a.compareTo(b) == 0 iff a == b), but this is not a requirement. For example, double and DateTime have compareTo methods that do not agree with operator operator ==. For doubles the compareTo method is more precise than the equality, and for DateTime it is less precise.

Examples:

dart
(0.0).compareTo(-0.0);   // => 1
0.0 == -0.0;             // => true
var now = DateTime.now();
var utcNow = now.toUtc();
now == utcNow;           // => false
now.compareTo(utcNow);   // => 0

The Comparable interface does not imply the existence of the comparison operators <, <=, > and >=. These should only be defined if the ordering is a less-than/greater-than ordering, that is, an ordering where you would naturally use the words "less than" about the order of two elements.

If the equality operator and compareTo disagree, the comparison operators should follow the equality operator, and will likely also disagree with compareTo. Otherwise they should match the compareTo method, so that a < b iff a.compareTo(b) < 0.

The double class defines comparison operators that are compatible with equality. The operators differ from double.compareTo on -0.0 and NaN.

The DateTime class has no comparison operators, instead it has the more precisely named DateTime.isBefore and DateTime.isAfter, which both agree with DateTime.compareTo.

Properties

hashCode no setter inherited

int get hashCode

The hash code for this object.

A hash code is a single integer which represents the state of the object that affects operator == comparisons.

All objects have hash codes. The default hash code implemented by Object represents only the identity of the object, the same way as the default operator == implementation only considers objects equal if they are identical (see identityHashCode).

If operator == is overridden to use the object state instead, the hash code must also be changed to represent that state, otherwise the object cannot be used in hash based data structures like the default Set and Map implementations.

Hash codes must be the same for objects that are equal to each other according to operator ==. The hash code of an object should only change if the object changes in a way that affects equality. There are no further requirements for the hash codes. They need not be consistent between executions of the same program and there are no distribution guarantees.

Objects that are not equal are allowed to have the same hash code. It is even technically allowed that all instances have the same hash code, but if clashes happen too often, it may reduce the efficiency of hash-based data structures like HashSet or HashMap.

If a subclass overrides hashCode, it should override the operator == operator as well to maintain consistency.

Inherited from Object.

Implementation
dart
external int get hashCode;

runtimeType no setter inherited

Type get runtimeType

A representation of the runtime type of the object.

Inherited from Object.

Implementation
dart
external Type get runtimeType;

Methods

compareTo()

int compareTo(T other)

Compares this object to another object.

Returns a value like a Comparator when comparing this to other. That is, it returns a negative integer if this is ordered before other, a positive integer if this is ordered after other, and zero if this and other are ordered together.

The other argument must be a value that is comparable to this object.

Implementation
dart
int compareTo(T other);

noSuchMethod() inherited

dynamic noSuchMethod(Invocation invocation)

Invoked when a nonexistent method or property is accessed.

A dynamic member invocation can attempt to call a member which doesn't exist on the receiving object. Example:

dart
dynamic object = 1;
object.add(42); // Statically allowed, run-time error

This invalid code will invoke the noSuchMethod method of the integer 1 with an Invocation representing the .add(42) call and arguments (which then throws).

Classes can override noSuchMethod to provide custom behavior for such invalid dynamic invocations.

A class with a non-default noSuchMethod invocation can also omit implementations for members of its interface. Example:

dart
class MockList<T> implements List<T> {
  noSuchMethod(Invocation invocation) {
    log(invocation);
    super.noSuchMethod(invocation); // Will throw.
  }
}
void main() {
  MockList().add(42);
}

This code has no compile-time warnings or errors even though the MockList class has no concrete implementation of any of the List interface methods. Calls to List methods are forwarded to noSuchMethod, so this code will log an invocation similar to Invocation.method(#add, [42]) and then throw.

If a value is returned from noSuchMethod, it becomes the result of the original invocation. If the value is not of a type that can be returned by the original invocation, a type error occurs at the invocation.

The default behavior is to throw a NoSuchMethodError.

Inherited from Object.

Implementation
dart
@pragma("vm:entry-point")
@pragma("wasm:entry-point")
external dynamic noSuchMethod(Invocation invocation);

toString() inherited

String toString()

A string representation of this object.

Some classes have a default textual representation, often paired with a static parse function (like int.parse). These classes will provide the textual representation as their string representation.

Other classes have no meaningful textual representation that a program will care about. Such classes will typically override toString to provide useful information when inspecting the object, mainly for debugging or logging.

Inherited from Object.

Implementation
dart
external String toString();

Operators

operator ==() inherited

bool operator ==(Object other)

The equality operator.

The default behavior for all Objects is to return true if and only if this object and other are the same object.

Override this method to specify a different equality relation on a class. The overriding method must still be an equivalence relation. That is, it must be:

  • Total: It must return a boolean for all arguments. It should never throw.

  • Reflexive: For all objects o, o == o must be true.

  • Symmetric: For all objects o1 and o2, o1 == o2 and o2 == o1 must either both be true, or both be false.

  • Transitive: For all objects o1, o2, and o3, if o1 == o2 and o2 == o3 are true, then o1 == o3 must be true.

The method should also be consistent over time, so whether two objects are equal should only change if at least one of the objects was modified.

If a subclass overrides the equality operator, it should override the hashCode method as well to maintain consistency.

Inherited from Object.

Implementation
dart
external bool operator ==(Object other);

Static Methods

compare()

int compare(Comparable<dynamic> a, Comparable<dynamic> b)

A Comparator that compares one comparable to another.

It returns the result of a.compareTo(b). The call may fail at run-time if a is not comparable to the type of b.

This utility function is used as the default comparator for ordering collections, for example in the List sort function.

Implementation
dart
static int compare(Comparable a, Comparable b) => a.compareTo(b);