# Java/Comparable

### From charlesreid1

Comparable is the interface that is implemented in order for objects to be comparable using operators like < > == etc.

https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html

This is a generic type interface, and can be used to define a class that can be compared using custom criteria. For example, we can organize a list according to a very specific method of ordering (right-to-left, filling in with "ghost" titles, as in the Classy problem), or according to custom criteria like when a Cartesian (x,y) point would be visited by a space-filling curve, as with the Hilbert Sort problem.

## Comparable example

Here is an example implemented for an (x,y) Cartesian point that compares two points by saying a > b if the line connecting a to b is positive, and a < b if the line connecting a to b is negative.

To do this, we just take delta x times delta y. If one or the other is negative, the slope is negative. If both or neither is negative, the slope is positive.

public class Point extends Comparable<Point> { double x, y; public int compareTo(Point p2) { return (this.x - p2.x) * (this.y - p2.y); } }

## Flag

Computer SciencePart of the 2017 CS Study Plan.
Builtin features of Java: Java/Exceptions Java/Generics Java/Iterators Java/Comparators Java/Numeric Documentation: Javadocs Tools and functionality: Java/URLs External libraries: Apache Commons OOP: OOP Checklist
· Template:CSFlag · e |

See also: