Questions tagged [comparable]

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)
}
1251 questions
14
votes
3 answers

Implementing Comparable, compareTo name clash: "have the same erasure, yet neither overrides the other"

I'd like to have a compareTo method that takes a Real (a class for working with arbitrarily large and precise real numbers [well, as long as it's less than 2^31 in length at the moment]) and a compareTo method that takes an Object, but Java isn't…
Jxek
  • 502
  • 1
  • 4
  • 13
14
votes
2 answers

What type of Exception should I throw if the wrong type of object is passed?

What type of Exception should I throw if the wrong type of object is passed into my compareTo method? ClassCastException?
ritch
  • 1,760
  • 14
  • 37
  • 65
13
votes
3 answers

Java error: "Comparison method violates its general contract!"

I have this code: package org.optimization.geneticAlgorithm; import org.optimization.geneticAlgorithm.selection.Pair; public abstract class Chromosome implements Comparable { public abstract double fitness(); public abstract…
mariolpantunes
  • 1,114
  • 2
  • 15
  • 28
13
votes
4 answers

C++ determine if class is comparable

I'm more or less Java programmer, so this might be a stupid question, but I didn't manage to find any simple solution. I have a class like this in C++: template class Node {...} And I need T to be comparable - to have at least == < >…
Jaa-c
  • 5,017
  • 4
  • 34
  • 64
13
votes
2 answers

Java 8: implementing Comparable

I like the new static factory methods of Comparator, as they allow to implement Comparators in a very concise and less error-prone way. But what is the recommended way to implement Comparable? Should we use Comparators inside the Comparable…
Puce
  • 37,247
  • 13
  • 80
  • 152
13
votes
1 answer

Passing an instance of Comparable to a method that expects a Comparator

The Stream class in Java 8 defines a max method that requires a Comparator argument. Here is the method signature: Optional max(Comparator comparator) Comparator is a functional interface that has an abstract compare method with this…
Bryan
  • 133
  • 1
  • 6
13
votes
1 answer

Java Generics: compareTo and "capture#1-of ?"

The following gives me an error message: public static List> merge(Set>> lists) { List> result = new LinkedList>(); HashBiMap>, Integer> location =…
Nick Heiner
  • 119,074
  • 188
  • 476
  • 699
12
votes
5 answers

LINQ: Use .Except() on collections of different types by making them convertible/comparable?

Given two lists of different types, is it possible to make those types convertible between or comparable to each other (eg with a TypeConverter or similar) so that a LINQ query can compare them? I've seen other similar questions on SO but nothing…
James Cadd
  • 12,136
  • 30
  • 85
  • 134
12
votes
3 answers

How to implement an interface with an enum, where the interface extends Comparable?

Consider this code: public interface Foo extends Comparable {} public enum FooImpl implements Foo {} Due to the restrictions of type erasure, I receive the following error: java.lang.Comparable cannot be inherited with different arguments:…
soc
  • 27,983
  • 20
  • 111
  • 215
12
votes
4 answers

Help comparing float member variables using Comparators

I am able to compare Strings fine, but would like to know how I can rank floating point numbers? getChange() returns a String. I want to be able to sort descending. How can I do this? UPDATE: package org.stocktwits.helper; import…
Sheehan Alam
  • 60,111
  • 124
  • 355
  • 556
12
votes
3 answers

How does compareTo work?

I know that compareTo returns a negative or positive result on how well one string correlates to the other, but then why: public class Test { public static void main(String[] args) { String y = "ab2"; if(y.compareTo("ac3") == -1)…
Harsh
  • 121
  • 1
  • 1
  • 3
12
votes
4 answers

Cannot invoke compareTo(double) on the primitive type double

The line return array[index1].compareTo(array[index2]); provides an error "Cannot invoke compareTo(double) on the primitive type double". How to solve this issue? /*:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::*/ /*:: This…
Klausos Klausos
  • 15,308
  • 51
  • 135
  • 217
11
votes
4 answers

Implements Comparable to get alphabetical sort with Strings

I would like an object to be comparable (to use it in a TreeSet in that case). My object got a name field and I would like it to be sorted by alphabetical order. I thought first that I could use the unicode value of the string and simply do a…
Silver Duck
  • 581
  • 1
  • 5
  • 18
11
votes
2 answers

java "not comparable" exception?

I'm making a custom class that implements comparable, and I'd like to throw some kind of exception if somebody tries to compare two objects that are not comparable by my definition. Is there a suitable exception already in the API, or do I need to…
Mirrana
  • 1,601
  • 6
  • 28
  • 66
11
votes
1 answer

Equals and Comparable with Sets

I posted some code here which correctly solved a problem the poster had. OP wanted to remove duplicates and bring certain special items to the top of a list. I used a TreeSet with a special Comparable class which wrapped the Locale they were working…
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213