Java Comparable Interface & compareTo Method

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.