Programming Examples

Are you a Programmer or Application Developer or a DBA? Take a cup of coffee, sit back and spend few minutes here :)

Tag Archive for ‘Comparable’

Java Comparable Interface & compareTo Method

Comparing Object Via Comparable Interface - Explained

We used TreeSet class in the past example on the Integer boxed type. The TreeSet knows how to compare two Integer boxed type because the Java Integer class implements Comparable interface. For user-defined types, one should sign the the Comparable interface contract so that Java Collection class like TreeSet knows how to compare two objects and choose which one is bigger. The Comparable interface has a contract method compareTo which will study two objects and returns an integer. This integer value is helpful to know the object bigger or smaller or equal with the compared object. In this example, we will use the Java TreeSet to store Product objects.

Continue Reading →