-3

I'd like to know what the interface Comparable compares in Java. Let's say I have two Nodes with only one instance variable each. How come node1.compareTo(node2) works?

Thanks!

Amir David
  • 33
  • 2

2 Answers2

1

Comparable is an interface, and as such it contains no logic. A concrete class with implement Comparable must implement the .compareTo() method, as detailed here.

Implementing this interface means you intend the class to be able to compare itself with another instance, and return a numeric value representing if it should be considered "greater" or "less" than the instance passed in. This is often used with sorting in collections.

For example:

public class Node implements Comparable<Node> {

    private int id;
    private String name;

    public int compareTo(Node other) {
       return (this.id < other.id ) ? -1 : (this.id > other.id) ? 1 : 0;
    } 
}
Louis Wasserman
  • 191,574
  • 25
  • 345
  • 413
seanhodges
  • 17,426
  • 15
  • 71
  • 93
0

First, read the documentation.

This interface imposes a total ordering on the objects of each class that implements it. This ordering is referred to as the class's natural ordering, and the class's compareTo method is referred to as its natural comparison method.

The documentation of the compareTo() method:

Compares this object with the specified object for order. Returns a negative integer, zero, or a positive integer as this object is less than, equal to, or greater than the specified object.

Here is a sample :

public class MyComparable implements Comparable< MyComparable >{

   private int value;

   @Override
   public int compareTo( MyComparable other ) {
      return this.value - other.value;
   }

   public MyComparable( int i ) {
      value = i;
   }

   public static void main( String[] args ) {
      MyComparable _12    = new MyComparable( 12 );
      MyComparable _42    = new MyComparable( 42 );
      MyComparable _12bis = new MyComparable( 12 );
      System.out.println( _12.compareTo( _42 ));
      System.out.println( _42.compareTo( _12 ));
      System.out.println( _12.compareTo( _12bis ));
   }
}

It ouputs:

-30
30
0
  • -30 (<0) means 12 < 42, no surprise
  • 30 (>0) means 42 > 12, ok
  • 0 (=0) means 12 equals 12, seems correct
Aubin
  • 14,617
  • 9
  • 61
  • 84