Home | FAQ | Contact me

Java Comparable

Using Comparable gets you the ability to submit your object to Collections.sort(). This is an example. Moreover, this example sorts not only on one field, but two.

import java.lang.Comparable;

abstract class Thing implements Comparable< Thing >
{
  String name;
  int    start;
  int    stop;

  public int compareTo( Thing thing )
  {
    int startDifference = this.start - this.stop;

    if( startDifference != 0 )
      return startDifference;

    return this.stop - thing.stop;
  }
}

Once you've create a List of Things, in any order, you can sort that list this way:

import java.util.Collections;

...

Collections.sort( thingList );