Addition to Comparable interface (original) (raw)

Roy van Rijn roy.van.rijn at gmail.com
Tue Mar 31 05:16:14 PDT 2009


FEATURE SUMMARY:

The return value of the Comparable interfae could be made a lot clearer if it would have the following static variables:  public static int BEFORE = -1;  public static int EQUAL = 0;  public static int AFTER = 1; This might give the impression that the only values returned by compareTo are -1, 0, 1 which is certainly not true. The interface only requires that the sign of the returned value reflect the ordering.

That might be a problem indeed, but the javadoc should still indicate its possible to use any positive and negative integer value.

The problem I've seen a lot is the following, even in large corporate programs, when people compare integers like this:

import java.util.ArrayList; import java.util.Collections; import java.util.List;

public class Compare implements Comparable {

int number;
public Compare(int nr) {
    this.number = nr;
}

public static void main(String args[]) {
    System.out.println("Testing order:");
    List<Compare> compareList = new ArrayList<Compare>();
    compareList.add(new Compare(Integer.MIN_VALUE));
    compareList.add(new Compare(Integer.MAX_VALUE));
    compareList.add(new Compare(-100000));
    compareList.add(new Compare(100000));
    compareList.add(new Compare(300000));
    compareList.add(new Compare(200000));
    compareList.add(new Compare(2147473647)); //Some large value
    compareList.add(new Compare(-2147473648)); //Some other large

negative number Collections.sort(compareList);

    for(Compare sorted:compareList) {
        System.out.println(sorted.getNumber());
    }
}

public int getNumber() {
    return number;
}

public int compareTo(Object o) {
    if(o instanceof Compare && o != null) {
        return this.getNumber() - ((Compare)o).getNumber();

//compareTo with minus, used too much...! } return 0; } }

Returns something like: 2147483647 -2147483648 -100000 100000 200000 300000 2147473647 -2147473648

Not really ordered because people forget the boundaries of the integer! So having an enum instead, forcing a triple return value would be much better. And this comes pretty close without breaking any code. The only reason I know this method returns an integer is because of simplicity and not wanting to make a triple-value return value (correct me if I'm wrong!).

Roy van Rijn



More information about the coin-dev mailing list