# Implement Comparable interface

• 11-07-2011, 07:30 AM
JojoDiaz
Implement Comparable interface
Hey everyone,

I'm supposed to use class Circle so it implements the Comparable interface.

the output should look like this,

Circle(3.00)
Circle(4.00)
Circle(3.01)
Circle(1.00)
Circle(2.00)
Circle(2.99)

then arrays.sort(Circles) will make it look like

Circle(1.00)
Circle(2.00)
Circle(2.99)

My teacher said to use Math.signum but i have no idea how to implement that into my code. Here is what i have
Code:

```import java.util.Arrays; ///////////////////////////////////////////////////////////////////////// class Hw11 { //-----------------------------------------------------------------------   public static void main ( String [] args ) throws Exception   {       Circle[] circles = { new Circle(3),                           new Circle(4),                           new Circle(3.01),                           new Circle(1),                           new Circle(2),                           new Circle(2.99) };       for ( Circle c : circles ) System.out.println(c);       Arrays.sort(circles);       System.out.println();       for ( Circle c : circles ) System.out.println(c);   } //----------------------------------------------------------------------- } // end class Hw14 ///////////////////////////////////////////////////////////////////////// class Circle implements Comparable {   private double radius;   public Circle (double radius)   {       this.radius = radius;   }   public int compareTo (Object c)   {       Circle that = (Circle) c;       return (int)( this.radius - that.radius );   }   public String toString ()   {       return String.format("%s%.2f%s", "Circle(",radius,")");   }   }// end class Circle /////////////////////////////////////////////////////////////////////////```
• 11-07-2011, 07:54 AM
JojoDiaz
Re: Implement Comparable interface
• 11-07-2011, 07:59 AM
camickr
Re: Implement Comparable interface
Does your sort work? What happens when you cast a "double" to an "int"? You get truncation so you are returning an incorrect value from the compareTo() method.

signum() is just a method that converts any negative value to -1 and any positive value to +1, so now when you cast from a double to an int you don't have to worry about truncation.

Here is some simple code for you to play with:
Code:

```public class Test {         public static void main(String args[]) throws Exception         {                 double a = 2.1;                 double b = 3.0;                 double c = b - a;                 System.out.println( c );                 System.out.println( (int)c );                 System.out.println( (int)Math.signum(c) );         } }```
Quote: