Contents    Page-10    Prev    Next    Page+10    Index   

Comparator in Java

Java does not allow a function to be passed as a function argument, but there is a way to get around this restriction by passing in an object that defines the desired function as a method (sometimes called a functor). A Comparator is a class of object that defines a method compare.

A comparison is basically a subtraction; the compare method returns an int that gives the sign of the subtraction (the value of the int does not matter). If cmp is a Comparator,, y) will be:

- x < y
0 x = y
+ x > y

A simple comparator can simply subtract properties of the objects:

public static void
  mySort( AnyType[] a,
          Comparator<? super AnyType> cmp) {...}

class MyOrder implements Comparator<MyObject> {
  public int compare(MyObject x, MyObject y)
    { return ( - ); }}