Question

Must I always adhere to the contract established for Comparable Interface? Is there acceptable leverage when all three cases of the contract are unclear?

The contract simply states:

If this object precedes that; return negative value
If this object equals that; return zero
If this object proceeds that; return positive value 

I desire to compare two points which are Point2D objects. Comparing two points using the distance(Point2D point) behavior makes a compareTo() appear binary; Either two points have a zero distance or their distance is nonzero.

If I were to write such a compareTo() behavior that overrides the default, perhaps it would be as follows:

private Point2D location;

public int compareTo(Object o)
{
    if(this.getLocation().distance(o.getLocation() == 0)
    {
        return 0;
    }
    else
    {
        return 1;
    }
}

Perhaps comparing two Point2D objects would be better suited using simple behavior testing distance and not bother implementing Comparable. There may even be a way to adhere to the contract I do not know.

Was it helpful?

Solution 2

Always adhere strictly to the contract of an interface you implement, especially one such as Comparable that's defined in the core API. If you can't define a total order on your type such that the comparison of two objects is always stable and that transitive comparison is always stable, your class will cause runtime failures in code that can be far removed from your class, especially if your objects are added to a Set.

Your use case really doesn't sound like you're describing an ordering of the elements, but rather some kind of equals; Comparable/Comparator seems to be the wrong approach entirely.

OTHER TIPS

It sounds like implementing Comparable doesn't make sense for this use case. On the other hand, one possible variant on this approach would be Comparator<Point2D> closestTo(Point2D point), which would compare two points A and B by which is closer to a third point C.

The method you're describing would, essentially, be an equals method -- in which case, you should just override equals with that behavior. There's no sense in making that a comparison.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top