In Java, this interface is implemented by a class to indicate that it can be compared to another object and therefore ordered. In Go, comparable is a predeclared interface constraint for generic types that support == and != operators. Make sure to use the appropriate language tag along with this.
In Java, this interface is implemented by a class to indicate that it can be compared to another object and therefore ordered. The interface defines one method: compareTo()
. Classes can either implement it as a raw type, as with older versions of Java:
public class MyClass implements Comparable
{
public int compareTo(Object other)
{
MyClass toCompare = (MyClass) other;
//...
}
}
Or, as of Java 1.5, a class can use generics:
public class MyClass implements Comparable<MyClass>
{
public int compareTo(MyClass other)
{
//...
}
}
The general contract of compareTo()
is:
- If
this
is less than the parameter, it returns a value less than zero. - If
this
is greater than the parameter, it returns a value greater than zero. - Otherwise, if
this
is equal to the parameter, returns zero.
The actual value of compareTo()
is irrelevant; only the sign of the return value matters.
Javadoc for java.lang.Comparable
In Go, comparable
is a predeclared interface constraint. It can be used directly or it can be embedded in other interface constraints. It cannot be used in union terms. Specifications: Type Constraints:
The predeclared interface type comparable denotes the set of all concrete (non-interface) types that are comparable. Specifically, a type T implements comparable if:
- T is not an interface type and T supports the operations == and !=; or
- T is an interface type and each type in T's type set implements comparable.
Example usage:
func IsZero[T comparable](v T) bool {
return v == *new(T)
}