Java Interface Comparator static compare

2019-06-23 17:06发布

问题:

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:

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))


回答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.



回答3:

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);
}