The Comparable
interface is used to compare two objects and their order. As per the Javadocs, the compareTo
method should return 0
if the two objects are equal, any negative number if this
object is “smaller” than the specified other, and any positive number if this
object is “larger” than the specified other. What “smaller” and “larger” means is entirely dependent on what you’re trying to model – for Strings, for example, “greater than” and “less than” refer to their alphabetic ordering, while for Integers it refers to their natural ordering.
In your case, by always returning 4
, you’re claiming that 1) the objects are not equal, and 2) both objects are larger than the other (which doesn’t really make sense semantically, but if it works for you, whatever).
solved java how compare function works