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
23
votes
4 answers

What does comparison being consistent with equals mean ? What can possibly happen if my class doesn't follow this principle?

From the JavaDoc of TreeMap : Note that the ordering maintained by a sorted map (whether or not an explicit comparator is provided) must be consistent with equals if this sorted map is to correctly implement the Map interface. (See Comparable…
Geek
  • 26,489
  • 43
  • 149
  • 227
22
votes
4 answers

How to get min/max from ArrayList based on its object attribute values?

What I want to achieve is to get min/max attribute value of object from ArrayList. For example if Object has attribute weight(float), I want heaviest object from the list. I've tried to implement Comparable to get max/min value but this…
martin1337
  • 2,384
  • 6
  • 38
  • 85
21
votes
6 answers

Create a compareTo to a Generic Class that Implements Comparable

I have a Generic Class with two type variables, which implements java.lang.Comparable. public class DoubleKey implements Comparable>{ private K key1; private J key2; public DoubleKey(K key1, J key2){ …
John Bautista
  • 1,480
  • 3
  • 29
  • 60
21
votes
2 answers

Why does Arrays.sort take Object[] rather than Comparable[]?

I was wondering why the sort method of the Arrays class is asking for a parameter of type Object[]. Why the parameter is not of type Comparable[]. If you don't pass a Comparable[] it's generating a ClassCastException. Why ... public static void…
Joel
  • 339
  • 2
  • 11
20
votes
3 answers

ordering a hashset example?

I need an example on how to use a comparable class on a HashSet to get an ascending order. Let’s say I have a HashSet like this one: HashSet hs = new HashSet(); How can I get hs to be in ascending order?
Jony
  • 6,694
  • 20
  • 61
  • 71
20
votes
4 answers

Java Sorting: sort an array of objects by property, object not allowed to use Comparable

I have a class, Library, that contains an array of Book objects, and I need to sort the array based off the properties of Book, either Title or PageNumber. The problem is im not allowed to use the Comparable class with Book. How would you recommend…
samuraiseoul
  • 2,888
  • 9
  • 45
  • 65
18
votes
5 answers

How to implement a generic `max(Comparable a, Comparable b)` function in Java?

I'm trying to write a generic max function that takes two Comparables. So far I have public static > T max(T a, T b) { if (a == null) { if (b == null) return a; else return b; } if (b == null) …
Duncan McGregor
  • 17,665
  • 12
  • 64
  • 118
18
votes
7 answers

How to implement Comparable so it is consistent with identity-equality

I have a class for which equality (as per equals()) must be defined by the object identity, i.e. this == other. I want to implement Comparable to order such objects (say by some getName() property). To be consistent with equals(), compareTo() must…
Balz Guenat
  • 1,552
  • 2
  • 15
  • 35
17
votes
1 answer

comparing and thenComparing gives compile error

I am trying to sort List of employees by name then age using Java8 Comparator, I have created below Comparator but it gives me a compiler error Type mismatch: cannot convert from Comparator to Comparator c =…
Saravana
  • 12,647
  • 2
  • 39
  • 57
17
votes
2 answers

Should Comparable ever compare to another type?

I'm wondering if there's ever a valid use case for the following: class Base {} class A implements Comparable { //... } It seems to be a common pattern (see Collections for a number of examples) to accept a collection of type T, where T…
shmosel
  • 49,289
  • 6
  • 73
  • 138
15
votes
3 answers

how can I implement Comparable more than once?

I'm upgrading some code to Java 5 and am clearly not understanding something with Generics. I have other classes which implement Comparable once, which I've been able to implement. But now I've got a class which, due to inheritance, ends up trying…
user26270
  • 6,904
  • 13
  • 62
  • 94
14
votes
3 answers

Cannot use comparable with father-son-grandson inheritance

Given the following code : public abstract class Participant { private String fullName; public Participant(String newFullName) { this.fullName = new String(newFullName); } // some more code } public class Player extends…
JAN
  • 21,236
  • 66
  • 181
  • 318
14
votes
3 answers

Go with Generics: type parameter T is not comparable with ==

I am playing around with Go Generics in the playground, trying to write some generic array functions. https://gotipplay.golang.org/p/vS7f_Vxxy2j package main import ( "fmt" ) func array_has[T any](haystack []T, needle T) bool { for _, val…
Tasos Bitsios
  • 2,699
  • 1
  • 16
  • 22
14
votes
6 answers

How to override compareTo (Java)

I'm a beginner in programming and I have two classes. First class is: public class User implements Comparable with field int age, constructor and overrided method of interface Comparable: @Override public int compareTo(User user) { …
aLittleMind
  • 183
  • 2
  • 3
  • 12
14
votes
3 answers

MyClass cannot be cast to java.lang.Comparable: java.lang.ClassCastException

I am doing a java project and I got this problem and don't know how to fix it. The classes in my project (simplified): public class Item { private String itemID; private Integer price; public Integer getPrice() { return…
user2234225
  • 149
  • 1
  • 1
  • 4
1 2
3
83 84