public class DefaultComparator<T> extends Object implements Comparator<T>
Comparator, which can compare
objects implementing Comparable.
Null-Friendly:
null is treated less than non-null.
ComparatorIf the objects compared doesn't implementcomp = new DefaultComparator (); System.out.println(comp.compareTo(null, "helloworld")); // prints -1 System.out.println(comp.compare("helloworld", null)); // prints 1 System.out.println(comp.compare(null, null)); // prints 0
Comparable, it throws
NotImplementedException.DefaultComparator for any objects that doesn't implement Comparable.
class Employee{
int marks;
int age;
public Employee(int marks, int age){
this.marks = marks;
this.age = age;
}
}
class EmployeeAgeComparator extends DefaultComparator{
@Override
protected int _compare(Employee emp1, Employee emp2){
return emp1.age - emp2.age;
}
}
the compare(...) method in DefaultComparator is final.
This method takes care of comparing values involving nulls. If both arguments are non-null,
then it delegates the comparison to _compare(...)
So it is guaranteed that, both arguments of _compare(...) are non-null.
| Constructor and Description |
|---|
DefaultComparator() |
| Modifier and Type | Method and Description |
|---|---|
protected int |
_compare(T o1,
T o2)
Arguments
o1 and o2 will be non-null |
int |
compare(T o1,
T o2)
this method can handle nulls ( null<non-null )
|
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, waitcomparing, comparing, comparingDouble, comparingInt, comparingLong, equals, naturalOrder, nullsFirst, nullsLast, reversed, reverseOrder, thenComparing, thenComparing, thenComparing, thenComparingDouble, thenComparingInt, thenComparingLongCopyright © 2021. All rights reserved.