Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java Interface Comparator static compare

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) ....
like image 434
Lorenzo Manucci Avatar asked Jul 26 '11 14:07

Lorenzo Manucci


People also ask

Does Comparator interface uses Compare method?

Java Comparator interface is used to order the objects of a user-defined class. This interface is found in java. util package and contains 2 methods compare(Object obj1,Object obj2) and equals(Object element).

Which is better Comparator or comparable in Java?

To summarize, if sorting of objects needs to be based on natural order then use Comparable whereas if you sorting needs to be done on attributes of different objects, then use Comparator in Java.

Can Comparator be static?

Java 8 introduced a few default methods and static factory methods on the Comparator interface using which developers can write Comparators in a declarative way.

Is compareTo static?

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.


2 Answers

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))
like image 152
Jon Skeet Avatar answered Oct 15 '22 04:10

Jon Skeet


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.

like image 20
Qwerky Avatar answered Oct 15 '22 04:10

Qwerky