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

List with Comparable Vs TreeSet

Option 1: Make a list which implements Comparable and sort it using collections.sort(List l) every time you add a value. Option 2: Make a TreeSet (which keeps itself sorted all the time). Which one will be faster? I am asking this because List gives…
aps
  • 2,452
  • 10
  • 35
  • 47
6
votes
2 answers

Write a comparable LINQ query for aggregate distinct count in sql?

I want to get a count for each month but count should be only at most one per day even if there are multiple occurences . I have the SQL query which works right but having trouble to convert it into LINQ - select count(DISTINCT DAY(date)) as…
Vishal
  • 12,133
  • 17
  • 82
  • 128
6
votes
7 answers

Quaternion Comparison?

Is quaternion comparison possible? I'm writing a Java class of Quaternions and I want to implement the Comparable interface to use the Collections.sort(List) facility. I'm not expert at math, I really don't understand the things I read…
anarhikos
  • 1,415
  • 3
  • 15
  • 19
6
votes
4 answers

How to do ordering of a sealed trait?

I have a distributed system defined by a sort of "state machine" ( "flow chart" ) each system writes there state in a shared "log" I'm representing each state as part of a sealed trait and a given "status" for that state I want to "merge/reduce" to…
Avba
  • 14,822
  • 20
  • 92
  • 192
6
votes
5 answers

Java: Compare/sort arbitrary objects

Is there anyway I can define a sequence/order for all objects in a JVM so that for any two distinct objects o1 or o2, there's a well defined rule that says either o1 > o2 or o2 > o1 and o1 == o2 if and only if they are the same…
RAY
  • 6,810
  • 6
  • 40
  • 67
6
votes
5 answers

Java compareTo method beginner level

I have an assignment where I need to create a Student class where you store the student's neptun code (String nep_c) and the number of points you have achieved in the exam (int point_num). Prepare a public int getMark () method that returns the…
Kicsi7
  • 63
  • 4
6
votes
6 answers

Java Collections.sort() not sorting as expected

I am trying to sort two different ArrayLists of objects by a specific atribute ('Student' objects by "program" and 'Professor' objects by "faculty"). Both classes extend my abstract 'Person' class. public abstract class Person implements…
6
votes
3 answers

Why does Collections.sort call Comparator twice with the same arguments?

I'm running an example to understand the behavior of Comparator in Java. import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; class HDTV { private int size; private String brand; public HDTV(int…
Anil Kumar
  • 2,521
  • 7
  • 23
  • 40
6
votes
3 answers

What is the best way to get min and max value from a list of Comparables that main contain null values?

I am thinking about something like this: public static > T minOf(T...ts){ SortedSet set = new TreeSet(Arrays.asList(ts)); return set.first(); } public static > T maxOf(T...ts){ …
user2427
  • 7,842
  • 19
  • 61
  • 71
6
votes
3 answers

Why Arrays.binarySearch(Object[],Object) takes Object args?

The method public static int binarySearch(Object[] a, Object key) of the Arrays class in its implementation navigates through the array argument a following the binarySearch algorithm and converts the elements of a into Comparable and invokes…
Mishax
  • 4,442
  • 5
  • 39
  • 63
6
votes
7 answers

in what way is a comparator superior to comparable?

"How will you sort collection of employee objects by its id or name". For that we can use two interfaces, i.e., Comparator and Comparable. seems this is one of the common interview questions But I don't see a reason why I should use both for…
brain storm
  • 30,124
  • 69
  • 225
  • 393
6
votes
5 answers

Do I need a equals and Hashcode method if my class implements comparable in Java?

I found this comment on can StringBuffer objects be keys in TreeSet in Java? "There are 2 identifying strategies used with Maps in Java (more-or-less). Hashing: An input "Foo" is converted into a best-as-possible attempt to generate a number that…
eagertoLearn
  • 9,772
  • 23
  • 80
  • 122
6
votes
1 answer

When using Collections.sort(), it sorts and prints the hashcode

I was working with one example where it uses ArrayList contains new instances and using Collections.sort() method using the comparable interface. I dont know why it prints out the hashcode when it sorts and where the bug in my code. Can anyone…
Java Beginer
  • 321
  • 2
  • 16
6
votes
4 answers

Sorting a list of non-comparable elements

Today I was asked this interview question: If I have a Person class with name, age and salary fields, and I put 100 new instances of this Person in an ArrayList, and then do Collections.sort(list), then on what parameter will the list be sorted? I…
Victor
  • 16,609
  • 71
  • 229
  • 409
6
votes
3 answers

Arrays.sort(object[]) is not throwing classcastexception

Code: public class CompareTest { public static void main(String[] args) { ArrayList list = new ArrayList(); (list).add(new CompareTest()); Arrays.sort(list.toArray()); //Does not throw Exception , why ? …
Sudhakar
  • 4,823
  • 2
  • 35
  • 42