Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
ordering
objects
communitycreator

When should a Java class implement the Comparable interface?

Frank M. Carrano

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

The order of objects

When you arrange a collection of objects one after the other, you get a total ordering of the objects. When this ordering seems obvious, we term it a natural ordering. For example, words have a natural alphabetical order, and numbers have a natural numeric order.

Objects with a natural order

Only classes of objects with a natural order should implement the Comparable interface. A programmer who uses such a class can assume that the method compareTo orders all of the class’s objects with one another in an expected, natural way.

Objects without a natural order

Classes of objects without a natural ordering are possible and not at all unusual. For example, it is straightforward to decide whether two addresses are equal, but to judge if one address is less than another is not. Thus, a class of addresses would not implement Comparable.

Although you could order cars by, for example, cost or color or brand, none of these orders is obviously preferable or natural.

However, a class of cars could have a method that compares two of its objects according to one of these criteria. You could name the method compareByColor, for instance, or even compareTo. But the class should not implement Comparable.

RELATED TAGS

java
ordering
objects
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring