jlibs.core.util
Class DefaultComparator<T>

java.lang.Object
  extended by jlibs.core.util.DefaultComparator<T>
All Implemented Interfaces:
Comparator<T>
Direct Known Subclasses:
FileNameComparator, FileTypeComparator, VisitingComparator

public class DefaultComparator<T>
extends Object
implements Comparator<T>

This is default implementation of Comparator, which can compare objects implementing Comparable.

Null-Friendly:

null is treated less than non-null.

 Comparator comp = 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
 
If the objects compared doesn't implement Comparable, it throws NotImplementedException.
You can extend DefaultComparator for any objects that doesn't implement Comparable.
For Example:
 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.

Author:
Santhosh Kumar T

Constructor Summary
DefaultComparator()
           
 
Method Summary
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 )
 
Methods inherited from class java.lang.Object
clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait
 
Methods inherited from interface java.util.Comparator
equals
 

Constructor Detail

DefaultComparator

public DefaultComparator()
Method Detail

compare

public final int compare(T o1,
                         T o2)
this method can handle nulls ( null<non-null )

Specified by:
compare in interface Comparator<T>

_compare

protected int _compare(T o1,
                       T o2)
Arguments o1 and o2 will be non-null



Copyright © 2018. All rights reserved.