5

int compare(Object o1, Object o2) Compares its two arguments for order.

For compare 2 objects o1 and o2 need do something like:

MyClass o1=new MyClass();
MyClass o2=new MyClass();

 if (o1.compare(o1,o2)>0) ......

Why this methtod not static? If method was static possible like:

 if (MyClass.compare(o1,o2)>0) ....
1
  • Jon's answer is right but your point is a good one. In theory it would be handy if every comparable class had a static 'compare' method, but there's no way to enforce that through an interface. Commented Jul 26, 2011 at 14:37

3 Answers 3

9

If it were static, how could it be called polymorphically? The point of Comparator is that you can pass an instance into something like sort... which has to then call the compare method on the comparator instance.

If a class is capable of comparing one instance of itself to another, it should implement Comparable instead, so you'd write:

if (o1.compareTo(o2))
Sign up to request clarification or add additional context in comments.

Comments

2

Your question shows a lack of understanding of Comparable and Comparator.

A Comparator is capable of comparing two other objects;

MyClass o1 = new MyClass();
MyClass o2 = new MyClass();
MyComparator c1 = new MyComparator();

if (c1.compare(o1, o2) > 0) {
  ...
}

Something which is Comparable is able to be compared to other objects;

MyClass o1 = new MyClass();
MyClass o2 = new MyClass();

if (o1.compareTo(o2)) > 0) {
  ...
}

It is very rare to compare a Comparator, so your example;

if (o1.compare(o1, o2) > 0) {
  ...
}

doesn't really make sense. Anyway, onto the answer, why isn't compareTo() static? Basically, Comparator is an interface, and interfaces can't have static methods. Why? Well, it doesn't make sense for them. An interface is about defining a contract, but providing no implementation.

Comments

1

The answer of John is fine unless null pointers are possible. If you want to support null pointers an option is to define a static method on some Util class

// null pointers first
public static int compareTo(@Nullable Comparable v1, @Nullable Comparable v2)
{
    return v1 == null ? (v2 == null ? 0 : -1) : v2 == null ? 1 : v1.compareTo(v2);
}
// null pointers last
public static int compareTo(@Nullable Comparable v1, @Nullable Comparable v2)
{
    return v1 == null ? (v2 == null ? 0 : 1) : v2 == null ? -1 : v1.compareTo(v2);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.