Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

Java Comparable example

In this tutorial we will discuss about comparable objects in the Java programming language. Java provides the Comparable interface, which contains only one method, called compareTo. This method compares two objects, in order to impose an order between them. Specifically, it returns a negative integer, zero, or a positive integer to indicate that the input object is less than, equal or greater than the existing object.

Moreover, Java provides the Comparator interface, which contains two methods, called compare and equals. The first method compares its two input arguments and imposes an order between them. It returns a negative integer, zero, or a positive integer to indicate that the first argument is less than, equal to, or greater than the second. The second method requires an Object as a parameter and aims to decide whether the input object is equal to the comparator. The method returns true, only if the specified object is also a comparator and it imposes the same ordering as the comparator.

A sample example using the Comparable interface is shown below:

Person.java:

public class Person implements Comparable {

    private String name;
    private int age;
    
    public Person(String name, int age) {
        this.name = name;
        this.age = age;
    }
    
    public int getAge() {
        return this.age;
    }
    
    public String getName() {
        return this.name;
    }

    @Override
    public String toString() {
        return "";
    }

    @Override
    public int compareTo(Person per) {
        if(this.age == per.age)
            return 0;
        else
            return this.age > per.age ? 1 : -1;
    }

    public static void main(String[] args) {
        Person e1 = new Person("Adam", 45);
        Person e2 = new Person("Steve", 60);
        
        int retval = e1.compareTo(e2);
        switch(retval) {
            case -1: {
                System.out.println("The " + e2.getName() + " is older!");
                break;
            }
            case 1: {
                System.out.println("The " + e1.getName() + " is older!");
                break;
            }
            default:
                System.out.println("The two persons are of the same age!");
        }
    }
}

In this example we created a class Person with two fields, name and age. This class implements the Comparable interface and thus, overrides the compareTo method. This method imposes an order between instances of the Person class, based on their age.

A sample execution is shown below:

Steve is older!

A sample example using the Comparator interface is shown below:

Company.java:

public class Company {
    private int num_of_employess;
    private String name;
    public Company(String name, int num_of_employess) {
        this.name = name;
        this.num_of_employess = num_of_employess;
    }
    
    public int getNumOfEmployess() {
        return this.num_of_employess;
    }
    
    public String getName() {
        return this.name;
    }
}

SortCompanies.java:

import java.util.Comparator;

public class SortCompanies implements Comparator {
    
    @Override
    public int compare(Company comp1, Company comp2) {        
        if(comp1.getNumOfEmployess()== comp2.getNumOfEmployess())
            return 0;
        else
            return comp1.getNumOfEmployess() > comp2.getNumOfEmployess() ? 1 : -1;
    }
    
    public static void main(String[] args) {
        Company comp1 = new Company("Company1", 20);
        Company comp2 = new Company("Company2", 15);
        
        SortCompanies sortCmp = new SortCompanies();
        
        int retval = sortCmp.compare(comp1, comp2);
        switch(retval) {
            case -1: {
                System.out.println("The " + comp2.getName() + " is bigger!");
                break;
            }
            case 1: {
                System.out.println("The " + comp1.getName() + " is bigger!");
                break;
            }
            default:
                System.out.println("The two companies are of the same size!");
        }
    }
}

In this example we first created a class Company that consists of the company’s name, along with its number of employees. Then, we created the SortCompanies class, which implements the Comparator interface and aims to impose an order between instances of the Company class, based on their number of employees.

A sample execution is shown below:

The Company1 is bigger!

Sort Collections

When a Java class implements the Comparable interface, then a collection of that object can be sorted automatically by using the Collections.sort or the Arrays.sort method. The collection will be sorted based on the natural order defined by the compareTo method.

A sample example that shows how to sort a collection of Comparable objects is shown below:

PersonCollections.java:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

public class PersonCollections {
	
	private static final int SIZE = 20;
	
	public static void main(String[] args) {
		List persons = new ArrayList(SIZE);
		
		// Create a number of persons with random age.
		Random rand = new Random();
		
		for(int i = 1; i <= SIZE; ++i) {
			int randAge = rand.nextInt(50) + 1;
			persons.add(new Person("Person" + i, randAge));
		}
		
		// Print all persons before ordering them.
		for(int i = 0; i < SIZE; ++i)
			System.out.println(persons.get(i).toString());
		System.out.println();
		
		// Sort the collection based on the age of each person.
		Collections.sort(persons);
		
		// Print all persons after ordering them.
		for(int i = 0; i < SIZE; ++i)
			System.out.println(persons.get(i).toString());
		System.out.println();
	}
}

In this example we created an ArrayList of Persons. For each instance of the Person class we created its age at random. Then, we sorted the collection, taking advantage of the fact that the Person class implements the Comparable inteface.

A sample execution is shown below:

<Person1, 35>
<Person2, 4>
<Person3, 39>
<Person4, 7>
<Person5, 48>
<Person6, 26>
<Person7, 2>
<Person8, 6>
<Person9, 31>
<Person10, 7>
<Person11, 47>
<Person12, 39>
<Person13, 1>
<Person14, 16>
<Person15, 11>
<Person16, 36>
<Person17, 32>
<Person18, 16>
<Person19, 10>
<Person20, 9>

<Person13, 1>
<Person7, 2>
<Person2, 4>
<Person8, 6>
<Person4, 7>
<Person10, 7>
<Person20, 9>
<Person19, 10>
<Person15, 11>
<Person14, 16>
<Person18, 16>
<Person6, 26>
<Person9, 31>
<Person17, 32>
<Person1, 35>
<Person16, 36>
<Person3, 39>
<Person12, 39>
<Person11, 47>
<Person5, 48>

Notice that the results will be different in every execution, due to the fact that we randomly generate the age field of each Person.

Final Comments

Those Objects that implement the Comparable interface in Java can be used as keys in a SortedMap or as elements in a SortedSet, without specifying any Comparator. A sample example to explain this observation is shown below:

TreeSetExample.java:

import java.util.Iterator;
import java.util.Random;
import java.util.TreeSet;

public class TreeSetExample {
	
	private static final int SIZE = 20;
	
	public static void main(String[] args) {
		TreeSet persons = new TreeSet();

		// Create a number of persons with random age.
		Random rand = new Random();

		for (int i = 1; i <= SIZE; ++i) {
			int randAge = rand.nextInt(50) + 1;
			persons.add(new Person("Person" + i, randAge));
		}
		
		// Print all persons.
		Iterator iter = persons.iterator();
		while(iter.hasNext())
			System.out.println(iter.next().toString());
	}
}

In this example we created a TreeSet of Persons. For each instance of the Person class we created its age at random. Then, we print each element of the collection, taking advantage of the fact that the Person class implements the Comparable inteface and the TreeSet maintains its elements sorted.

A sample execution is shown below:

<Person1, 6>
<Person9, 8>
<Person19, 11>
<Person17, 14>
<Person3, 15>
<Person16, 18>
<Person14, 21>
<Person13, 23>
<Person20, 25>
<Person6, 30>
<Person7, 33>
<Person10, 35>
<Person5, 36>
<Person4, 37>
<Person8, 42>
<Person12, 45>
<Person15, 49>
<Person2, 50>

Notice that the results will be different in every execution, due to the fact that we randomly generate the age field of each Person.

Download the Eclipse Project

The Eclipse project of this example: ComparableExample.zip.

 
This was a tutorial about comparable objects in Java.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close