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) ....
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).
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.
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.
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.
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))
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With