The Comparable interface of the Java library

  • The Java library contains many useful classes and interfaces (an interface is like an abstract class !)

  • A very useful interface is the Comparable interface defined as follows:

    public interface Comparable<E>   // Stored in java.lang package
    {
        public int compareTo(E o);
    } 

  • The documentation for the Comparable<T> interface is here:

  • Note:

    • The syntax <E> is called a generic in Java

    • This is an advanced Java feature that we have not studied

    • All you need to know is this feature can automate the downcasting operation for you.

The selection sort algorithm using Java's Comparable interface

We can use Java's Comparable interface to write the selection sort algorithm to sort Comparable objects:

    public static void selectionSort(Comparable[] list) 
    {
        for (int i = 0; i < list.length - 1; i++) 
	{
            int minIndex = findSmallest(list, i );

	    if ( minIndex != i ) 
	    {   // Swap list[minIndex] and list[i]
	        Comparable help = list[minIndex];
                list[minIndex] = list[i];
		list[i] = help;
            }
        }
    }

public static int findSmallest(Comparable[] myList, int start) { Comparable min; // smallest value in array int indexOfMin; // index where the smallest value is found // Find min value and its index min = myList[start]; // Assume first element is min indexOfMin = start; for ( int i = start+1; i < myList.length; i++ ) if ( myList[i].compareTo(min) < 0 ) // Found a larger element { min = myList[i]; // Update min value indexOfMin = i; } return indexOfMin; }

Implementing the Comparable interface for the BankAccount class

In order to use selectionSort( ) method with BankAccount objects, we must implement the Comparable interface:

public class BankAccount   // Original BankAccount class
{
    private double balance;

    public BankAccount(double x)
    {
        balance = x;
    }

    public double getBalance()
    {
        return balance;
    }

    // compareTo( ) used to compare 2 BankAccount objects

    public int compareTo( BankAccount other )
    {
        double diff = this.getBalance()
                      - other.getBalance();
        return (int) Math.signum(diff);
    }
} 

 

Implementing the Comparable interface for the BankAccount class

We change the BankAccount class to implement the Comparable interface:

public class BankAccount implements Comparable<BankAccount> 
{
    private double balance;

    public BankAccount(double x)
    {
        balance = x;
    }

    public double getBalance()
    {
        return balance;
    }

    // The generics feature allows us to use BankAccount as data type ! 

    public int compareTo( BankAccount other )
    {
        double diff = this.getBalance()
                      - other.getBalance();  // No error !
        return (int) Math.signum(diff);
    }
} 

The generic feature allows use to pass the data type BankAccount and avoid having to use downcasting !

Test program for selection sort algorithm for BankAccount objects

  • We can sort BankAccount objects using the selectionSort for Comparable:

        public static void main(String[] args)
        {
             BankAccount[] myList = new BankAccount[4];
             
             myList[0] = new BankAccount(400);
             myList[1] = new BankAccount(300);
             myList[2] = new BankAccount(500);
             myList[3] = new BankAccount(200);
             
             for ( int i = 0; i < myList.length; i++ )
                 System.out.print( myList[i].getBalance() + " ");
    	 System.out.println();
    
             selectionSort( myList );  // Uses upcasting !
    
             for ( int i = 0; i < myList.length; i++ )
                 System.out.print( myList[i].getBalance() + " ");
    	 System.out.println();
        }
      

The selectionSort() method will also work for Circle objects if Circle implements Comparable (next)

Implementing the Comparable interface for the Circle class

In order to use selectionSort( ) method with Circle objects, we must implement the Comparable interface:

public class Circle extends GeometricObject
{
    private double radius;

    Circle(double r)
    {
        radius = r;
    }

    public double getArea()
    {
        return 3.14159*radius*radius;
    }

    // compareTo( ) used to compare 2 Circle objects

    public int compareTo( Circle other )
    {
        double diff = this.getArea()
                      - other.getArea();
        return (int) Math.signum(diff);
    }
}

 

Implementing the Comparable interface for the Circle class

We change the Circle class to implement the Comparable interface:

public class Circle extends GeometricObject implements Comparable<Circle> 
{
    private double radius;

    Circle(double r)
    {
        radius = r;
    }

    public double getArea()
    {
        return 3.14159*radius*radius;
    }

    // The generics feature allows us to use Circle as data type ! 

    public int compareTo( Circle other )
    {
        double diff = this.getArea()
                      - other.getArea();  // No error !
        return (int) Math.signum(diff);
    }
} 

The generic feature allows use to pass the data type BankAccount and avoid having to use downcasting !

Test program for selection sort algorithm for Circle objects

  • We can sort Circle objects using the selectionSort for Comparable:

        public static void main(String[] args)
        {
             Circle[] myList = new Circle[4];
             
             myList[0] = new Circle("red", 4);
             myList[1] = new Circle("green", 3);
             myList[2] = new Circle("blue", 5);
             myList[3] = new Circle("yellow", 2);
             
             for ( int i = 0; i < myList.length; i++ )
                 System.out.print( myList[i].getArea() + " ");
    	 System.out.println();
    
             selectionSort( myList );  // Uses upcasting !
    
             for ( int i = 0; i < myList.length; i++ )
                 System.out.print( myList[i].getArea() + " ");
    	 System.out.println();
        }
      

The selectionSort() method will also work for Circle objects if Circle implements Comparable (next)

Java library methods that use the Comparable interface

  • The Java library has many classes used to store objects

  • We have studied one such classes: ()

        java.util.ArrayList 

    An ArrayList will only store data of object data types (i.e., it does not store data of primitive types)


  • An associated package called Collections () contains helpful methods for ArrayLists

  • The (static) sort( ) method can sort the objects stored in an ArrayList, but:

      • The object class must implement the Comparable interface in order to for the objects to be sorted !

Example to use Collections.sort( ) to sort an ArrayList of Integer

(1) We create an ArrayList for Integer (a wrapper class for int):

    public static void main(String[] args)
    {  
         ArrayList<Integer> myList = new ArrayList<>();
        
         myList.add(4);
         myList.add(3);
         myList.add(6);
         myList.add(2);
         
         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i) + " ");
	 System.out.println();

         Collections.sort( myList );  // Uses upcasting !

         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i) + " ");
	 System.out.println();
    } 

Note:   the Java Integer wrapper class has already implemented the Comparable interface (See: )

Example to use Collections.sort( ) to sort an ArrayList of Integer

(2) We insert a number of integers for testing:

    public static void main(String[] args)
    {  
         ArrayList<Integer> myList = new ArrayList<>();
     
         myList.add(4);
         myList.add(3);
         myList.add(6);
         myList.add(2);
      
         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i) + " ");
	 System.out.println();
      
         Collections.sort( myList );  // Uses upcasting !

         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i) + " ");
	 System.out.println();
    } 

Note:   the Java Integer wrapper class has already implemented the Comparable interface (See: )

Example to use Collections.sort( ) to sort an ArrayList of Integer

(3) We call Collection.sort( ) to sort the ArrayList of integers:

    public static void main(String[] args)
    {  
         ArrayList<Integer> myList = new ArrayList<>();

         myList.add(4);
         myList.add(3);
         myList.add(6);
         myList.add(2);

         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i) + " ");
	 System.out.println();
  
         Collections.sort( myList );  // Uses upcasting ! 

         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i) + " ");
	 System.out.println();
    } 

Note:   the Java Integer wrapper class has already implemented the Comparable interface (See: )

Example to use Collections.sort( ) to sort an ArrayList of Circle objects

We can use a similar program to sort an ArrayList of Circle objects:

    public static void main(String[] args)
    {  
         ArrayList<Circle> myList = new ArrayList<>();
         
         myList.add(new Circle("red", 4));
         myList.add(new Circle("green", 3));
         myList.add(new Circle("blue", 5));
         myList.add(new Circle("yellow", 2));
         
         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i).getArea() + " ");
	 System.out.println();

         Collections.sort( myList );  // Uses upcasting ! 

         for ( int i = 0; i < myList.size(); i++ )
             System.out.print( myList.get(i).getArea() + " ");
	 System.out.println();
    }
  

Note:   This will only work if the Circle class has implemented the Comparable interface !!

Another Java library methods that use the Comparable interface

  • We have studied arrays: ()

        Circle[] myList = new Circle[4]; 


  • An associated package called Arrays () contains helpful methods for arrays

  • The (static) sort( ) method can sort the objects stored in an array, but:

      • The object class must implement the Comparable interface in order to for the objects to be sorted !