Bright Java Tutorial

is brought to you by DoITBright LLC


Sort Objects In Java Using Comparable

It is very common that we will be needing to sort objects of the similar types according to ascending or descending order. Most of the time, we decide to do this sorting based on their unique identifier. If it happens that this is the case and our unique identifier is a numeric data type, the example provided below is a good way to accomplish the goal.

  package com.example.core;

  import java.util.ArrayList;
  import java.util.Collections;

   * This will demonstrate how to sort a list of objects
   * by implementing the Comparable interface.
   * Implementing the Comparable interface can be used
   * to sort according to a numeric value of an object 
   * property. In this case, we compared each object's id.
   * @author Rolan Liwanag
  public class SortByComparable 
      implements Comparable {
    int id;
    String desc;
    public static void main(String[] args) {
      //initialize an ArrayList to hold list of 
      //SortByComparable objects
      ArrayList listObj 
        = new ArrayList();
      //let us initialize our objects
      SortByComparable obj1 = new SortByComparable(); = 2;
      obj1.desc = "abc";
      SortByComparable obj2 = new SortByComparable(); = 1;
      obj2.desc = "bcd";
      //add the objects into the ArrayList
      //sort the objects
       * during sorting, since the object implemented 
       * the Comparable interface and overriden the 
       * compareTo method, then, the implementation 
       * that we provided for this class compareTo 
       * method will be invoked.
      for(SortByComparable obj : listObj) {
        System.out.println(" = " +;

    public int compareTo(SortByComparable comparestu) {
      //ascending order
      return -;
      //descending order
      //return -;


The above example is about a Class implementing the Comparable interface. Doing so, the class provided an implementation of the compareTo method. This method of sorting an object will only work with numeric data types.

Back    Next