I don't get the concept of compareTo. From what I read, since it is an interface, we get to decide how one object is compared to another (We define what it means for one object to be greater than, equal to, and less than another object). But when you use the compareTo method, it returns an integer. How does that connect? What do we do with that integer? How does this connect to the sort method? Example scenario: You are comparing two strings. You want to sort them so the string with the most letters goes first. Question: How do you set that up?
Let's get right to the heart of the matter. Imagine we have a class K
that we've defined as implementing Comparable<K>
, and two references a
and b
to objects of class K
.
To know if a
is "less thanb`, we write
if (a.compareTo(b) < 0) {
// compareTo returned a negative number
,,,
}
To know if a
is "equal to" b
, we write
if (a.compareTo(b) == 0) {
// compareTo returned zero
...
}
And to know if a
is "greater than" b
, we write
if (a.compareTo(b) > 0) {
// compareTo returned a positive integer
...
}
Does that clear things up a bit?