Click here to Skip to main content
14,022,571 members
Click here to Skip to main content
Add your own
alternative version


7 bookmarked
Posted 28 Dec 2013
Licenced CPOL

Comparator and Comparable objects.

, 29 Dec 2013
Rate this:
Please Sign up or sign in to vote.
Comparator and Comparable objects tutorial.


There is a lot of confusion among beginners about Comparators and Comparable.The main reason is the lack of understanding for what they are and the difference between them.


CompareTo – Method that compare between the current element that initiate the method and another object that passed in the method. The method returns positive number if current element is bigger than passed element, negative if it's smaller and 0 if they are equal.

Natural ordering – The most suitable parameter to be used to compare at the current class. Eg. Employee often compared by their "Performances".

Understanding Definitions


Object that can be compared with other objects by their narutal ordering.

Implementing Comparable means "I can compare myself with another object." This is typically useful when there's a single natural default comparison. © Jon Skeet.

Example: If i have an IdCard class than the natural ordering for this scenario is by Id number.


Independent specific class that targeted for comparing two objects by specific field.
Comparators allow us to add more ways for comparing objects.

Implementing Comparator means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type. © Jon Skeet.

Example: We can compare 2 Peoples by properties like Age, Height etc.


 public class Person implements Comparable<Object> {
    public int id;
    public String name;
    public int age;
    public int height;

    public Person(int id, String name, int age, int height) { = id; = name;
        this.age = age;
        this.height = height;

    public int compareTo(Object o) {
        return - ((Person)o).id;
    public String toString() {
        return String.format("[Name: %s/Age: %d/Height: %d]", name, age, height);

To illustrate the Comparable interface i choose to create a simple Person class. I gave this class a constructor with the following fields: id, name, age and height. I've used the Comparable<Object> interface and implemented it's compareTo method. Because Person object in my program is compared by id, I've implemented the compareTo to be subjected to the object id member. This can easily be changed to suit your own Class.We can know compare the person objects with others person objects, a comparison will look like this:

// Comparable
System.out.println("Is Bar id bigger than Sam ? " + pBar.compareTo(pSam)); 


System.out.println("Is Bar id bigger than Sam ? " + pBar.compareTo(pSam));
Another example: A Man's Wallet
We know that wallet will usually be compared by the amount of money it's containing. So a suitable Wallet class will look like this:
 public class Wallet implements Comparable<Object> {
    public int money = 0;
    public String name;
    public Wallet(String name, int money) { = name; = money;
    public int compareTo(Object o) {
        return - ((Wallet)o).money;


Comparators are independent classes which impelement "Comparator" interface.

Comparators main usages are for sorting each comparator will implement inside compareTo their own sort logic. And later the comparator will be passed through a sorting algorithm that will used the passed comparator sorting logic.

For example: HeightComparator will compare the height field from two objects.

 import java.util.Comparator;

public class HeightComparator implements Comparator<Object> {

    public int compare(Object o1, Object o2) {
        int p1 = ((Person)o1).height;
        int p2 = ((Person)o2).height;
        return p1 - p2;

This comparator is casting both received objects into Person objects and returning a positive number when first object is bigger than the second, else negative number when second object is bigger then the first one otherwise it returning zero because both of them are equal.

Comparator has another usage. We can use it without sorting the whole collection, by creating the targeted comparator and then passing it the objects we want to compare.

Exploring the examples

<span style="color: rgb(51, 51, 51); font-family: "Segoe UI", sans-serif; font-size: 10.5pt;"><code>

// Declaring Person objects.
ArrayList<Person> peoples = new ArrayList<Person>();
Person pOrel = new Person(1, "Orel", 27, 186);
Person pBar = new Person(2, "Bar", 28, 165);
Person pSam = new Person(3, "Sam", 25, 170);

I created an Person ArrayList to hold our collection. I've created 3 Person instances and added them into our collection.

// Comparable
System.out.println("Is Bar id bigger than Sam ? " + pBar.compareTo(pSam)); 

I've tested the Person compare method by comparing to see if pBar is bigger than pSam, as we know this will use Person compareTo method to see if pBar id number is bigger than pSam id number (false, pSam id is bigger).


Is Bar id bigger than Sam ? -1

// Comparators 2nd usage.
System.out.println("Does Orel taller than Sam ? " + new HeightComparator().compare(pOrel, pSam)); 

I've used specific comparator in order to discover if pOrel is taller than pSam.


Does Orel taller than Sam ? 16 

// Comparators 1st usage.
// Passing Collections sort methods our collection and the specified Comparator we want to use in order to sort the collection.
Collections.sort(peoples, new AgeComparator());
System.out.println("Compare by Age");

I'm passing our sorting algorithm peoples collection and AgeComparator in order to sort our collection by the logic inside the compare method inside AgeComparator. Than using a normal static method to print the result.


Compare by Age
[Name: Sam/Age: 25/Height: 170] [Name: Orel/Age: 27/Height: 186] [Name: Bar/Age: 28/Height: 165]  


Using Comparable and Comparators can easily simplifies your code when tasks for sorting are needed.
It will make you code more generic, readable and clean. 


  • 28th  December, 2013: Initial post. 


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Orel Eraki
Software Developer
Israel Israel
No Biography provided

You may also be interested in...

Comments and Discussions

PraiseGreat Post Pin
Member 1269832122-Aug-16 19:41
memberMember 1269832122-Aug-16 19:41 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web06 | 2.8.190417.4 | Last Updated 29 Dec 2013
Article Copyright 2013 by Orel Eraki
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid