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
10
votes
6 answers

Java - compareTo and operators

If I have a class Person that implements Comparable (compares personA.height to personB.height, for example), is it possible to use personA < personB as a substitute for personA.compareTo(personB) == -1? Are there any issues in doing…
Chet
  • 1,209
  • 1
  • 11
  • 29
10
votes
4 answers

Java - Make an object collection friendly

If an object holds a unique primary key, what interfaces does it need to implement in order to be collection friendly especially in terms of being efficiently sortable, hashable, etc...? If the primary key is a string, how are these interfaces best…
Chris Dutrow
  • 48,402
  • 65
  • 188
  • 258
10
votes
7 answers

Using Comparable for multiple dynamic fields of VO in java

I have a class public class StudentVO { int age; String name; } I used the same class in two different areas. At one place i need to sort based on the age. In another place I need to sort based on the name and in another place i may…
samba
  • 2,263
  • 2
  • 13
  • 13
10
votes
5 answers

Java "cannot cast to Comparable" when using TreeMap

Possible Duplicate: Java: SortedMap, TreeMap, Comparable? How to use? I am using the Java JungI graph package and Netbeans 7. I am getting the following error from Java: Exception in thread "main" java.lang.ClassCastException:…
CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216
9
votes
1 answer

What is Scala's Comparable trait?

I am searching for Scala counterpart of C# IComparable, and I found Comparable trait. I mean -- Comparable is mentioned, but when I search for it at http://www.scala-lang.org/api/current/scala/ I get 0 hits. Because of the name, using Google I get a…
greenoldman
  • 16,895
  • 26
  • 119
  • 185
9
votes
5 answers

Java: removing "Comparable is a raw type" warning

Suppose I have a method called foo taking 2 Object as parameter. Both objects are of the same type and both implements comparable interface. void foo(Object first, Object second){ if (!first.getClass().isInstance(second)) //first and second…
Heisenbug
  • 38,762
  • 28
  • 132
  • 190
9
votes
3 answers

Comparator .comparing().reversed() strange behaviour / not working as expected

As per my knowledge, Comparator.comparingInt() should sort in ascending order and Comparator.comparingInt().reversed should sort in descending order. But I found a scenario where this is inverse. This is better explained with an example. Following…
Arun Gowda
  • 2,721
  • 5
  • 29
  • 50
9
votes
8 answers

Java HashSet is allowing dupes; problem with comparable?

I've got a class, "Accumulator", that implements the Comparable compareTo method, and I'm trying to put these objects into a HashSet. When I add() to the HashSet, I don't see any activity in my compareTo method in the debugger, regardless of where I…
IVR Avenger
  • 15,090
  • 13
  • 46
  • 57
9
votes
2 answers

Does the specific signed integer matter when implementing compareTo in a Comparable class?

When implementing compareTo(), does the degree of "difference" need to be taken into account? For instance, if I have 3 objects, C1, C2, and C3, such that C1 < C2 < C3. Should C1.compareTo(C2) return an integer that is less than…
javanix
  • 1,270
  • 3
  • 24
  • 40
8
votes
4 answers

How do you implement compareTo methods cleanly?

Currently I am writing a compareTo method for quadratic functions in the form: ax^2 + bx + c. a, b, c are integer coefficients that are passed to the class through the constructor. In the compareTo method, I am supposed to first compare the…
CowZow
  • 1,275
  • 2
  • 17
  • 36
8
votes
1 answer

Ensure strict comparability at compile time in Go 1.20?

In Go 1.18 and Go 1.19 I can ensure at compile time that a type is strictly comparable, i.e. it supports == and != operators and those are guaranteed to not panic at run time. This is useful for example to avoid inadvertently adding fields to a…
blackgreen
  • 34,072
  • 23
  • 111
  • 129
8
votes
2 answers

Java8 Null-safe comparison

Having issues with comparing two products. I wish to compare the vintage (which is optional) attribute of each of them. But whenever this attribute is null, a NPE is thrown. I thought with Comparator.nullsLast(..) I can deal with null values... But…
Remo
  • 1,112
  • 2
  • 12
  • 25
8
votes
1 answer

Combining varargs and generics for chained comparisons in Java

Here's a tough nut to crack. I have a clash between using varargs and generics together. Following given code: public class MyObject implements Comparable { private String name; private int index; @Override public int…
Arceus
  • 520
  • 6
  • 16
8
votes
4 answers

Java priority queues and comparable interface

I've just been learning about priority queues and thought I'd try how it behaves with comparable interface. Code Snippet: import java.util.PriorityQueue; class kinga implements Comparable { double time=909.909; double d; public…
JohnnyHunter
  • 390
  • 1
  • 3
  • 16
8
votes
1 answer

Type aliasing ordered generics in Scala

I have a minimal definition of what a binary tree should look like: type Tree[T] = Option[Node[T]] case class Node[T](left: Tree[T], entry: T, right: Tree[T]) I now want to define a binary search tree as: type BST[T: Ordering] = Tree[T] but that…
pathikrit
  • 32,469
  • 37
  • 142
  • 221