|
Example program that uses Arrays.sort( ) to sort an array of Integer:
public static void main(String[] args)
{
Integer[] arr = new Integer[4];
arr[0] = 4;
arr[1] = 2;
arr[2] = 5;
arr[3] = 1;
for ( int i = 0; i < arr.length; i++ )
System.out.print( arr[i] + " ");
System.out.println();
Arrays.sort( arr ); // Sort array
for ( int i = 0; i < arr.length; i++ )
System.out.print( arr[i] + " ");
System.out.println();
}
|
DEMO: demo/05-interfaces/23-java-comparable/Demo.java
Note: we can use Arrays.sort( ) with an array of Integer because Integer implemented the Comparable interface
Suppose we use Arrays.sort( ) to sort and array of Circle objects:
public static void main(String[] args)
{
Circle[] arr = new Circle[4];
arr[0] = new Circle("red", 4);
arr[1] = new Circle("green", 3);
arr[2] = new Circle("blue", 5);
arr[3] = new Circle("yellow", 2);
for ( int i = 0; i < arr.length; i++ )
System.out.print( arr[i] + " , ");
System.out.println();
Arrays.sort( arr ); // Sort Circle objects...
for ( int i = 0; i < arr.length; i++ )
System.out.print( arr[i] + " , ");
System.out.println();
}
|
DEMO: demo/05-interfaces/23-java-comparable/Demo2.java + Circle.java --- compile and run: crash !!!
Why it crashed: the Circle class has not implemented the Comparable interface !!
In order to use the Arrays.sort( ) method with Circle objects, it must implement the Comparable interface:
public class Circle extends GeometricObject
{
private double radius;
// ... other method omitted for brevity
// Arrays.sort( ) will only work with Comparable objects
// The Circle class must implement the Comparable interface
// in order to use Arrays.sort( )
}
|
We must define the compareTo( ) method in the Circle class to implement the Comparable interface:
public class Circle extends GeometricObject implements Comparable<Circle> { private double radius; // ... other method omitted for brevity // Arrays.sort( ) will only work with Comparable objects // The Circle class must implement the Comparable interface // in order to use Arrays.sort( ) public int compareTo( Circle other ) { double diff = this.getArea() - other.getArea(); return (int) Math.signum(diff); // Convert to int: -1, 0 or +1 } } |
DEMO: demo/05-interfaces/24-java-comparable/Demo2.java + Circle.java
|