Thursday, April 18, 2013

Howto Use Java Comparator and Comparable by Example

In Java, there are some built-in methods that provides basic sorting of Primitive types array or Wrapper classes but what If we wanted to sort a custom class that we have written for use in one of our Projects? Well the answer is to write a sorting algorithm of our own and use it wherever it's required.

In Java, there are two interfaces that can help us achieve our goal. The reason the language provides two interfaces instead of one giving code developers enough flexibility to choose the one that they find suitable to their requirement.

The first Interface which I prefer to call is the Simple Handy Internal Sorter is available in java.lang.Comparable  . The Second Interface which I prefer to call is the Highly Flexible External Sorter is available in java.util.Comparator.

The former one is Simple and Internal as it needs to be implemented on the class itself and it's simple as it allows the code developers to write only single sorting implementation. The latter one is Highly Flexible and External that means it allows the code developer the flexibility to write as many as required sorting implementation for their custom class as it's declaration and implementation is in a separate class.

Let's start with the Below Example where Custom Class CarMake have both Simple Handy Internal Sorter and Highly Flexible External Sorter.

CarMake.java

As you can see below the Simple Handy Internal Sorter is already implemented on the Custom Class.


CarMakeComparatorAsc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.




CarMakeComparatorDesc.java

Custom Class CarMake's Highly Flexible External Sorter Implementation.


And, Finally the only thing required is to test both the implementation using a CarMakeSortTest.java.

CarMakeSortTest.java


I Hope this post helps you learn basics of Custom Class Sorting. Please do write your feedback...

You can download the complete code from Github