2004/11/24

Making Java Objects Comparable

by Budi Kurniawan
03/12/2003

In real life, objects are often comparable. For example, Dad's car is more expensive than Mom's, this dictionary is thicker than those books, Granny is older than Auntie Mollie (well, yeah, living objects, too, are comparable), and so forth. In writing object-oriented programs, there are often needs to compare instances of the same class. And once instances are comparable, they can be sorted. As an example, given two Employees, you may want to know which one has stayed in the organization longer. Or, in a search method for Person instances with a first name of Larry, you may want to display search results sorted by age. This article teaches you how to design your class to make its instances comparable by using the java.lang.Comparable and java.util.Comparator interfaces and presents three examples that illustrate both interfaces.

http://www.onjava.com/lpt/a/3286

No comments: