Reputation: 1667
I have created a Student
class, which contains roll number, name and age as its data variables. I created an ArrayList
for storing multiple objects of class Student
.
Now, I have used the Comparable
interface and its compareTo
method to sort the Student list data according to age.
Below is the compareTo
method I have created for sorting age wise:
public int compareTo(Student sNew)
{
return this.age-sNew.age;
}
Here, I can not understand, What is -
? and How it's working?
Because, I have also done it as below :
public int compareTo(Student sNew)
{
int returnValue=0;
if(this.age>sNew.age)
{
returnValue=1;
}else if(this.age<sNew.age){
returnValue=-1;
}else if(this.age==sNew.age)
{
returnValue=0;
}
return returnValue;
}
So, I have two doubts : How '-' is working in compareTo() method and where it returns the value (0,1,-1).
Please guide.
Upvotes: -1
Views: 1526
Reputation: 182
The Comparable
interface is the way Java performs a three-way comparison.
A trick to get sense of the semantics of compareTo
is: a.compareTo(b)
is equivalent to the question How is a compared to b? There can be only three answers (law of trichotomy): a is less than b (compareTo()
returns a less than zero value), a equals b (compareTo
returns a zero value), and a is greater than b (compareTo
returns a greater than zero value).
For the case of total order types (integers, floating-point numbers, dates, etc), the operation a - b always works because of:
In Java syntax, a is the current (this
object), so the syntax is a.compareTo(b)
, but the idea is the same.
Upvotes: 0
Reputation: 12953
The idea behind it is that compareTo
doesn't return 0,1,-1, but returns 0 (equals), positive number (bigger than) or negative (smaller).
For that reason, simply subtracting the ages will give you the correct answer
Upvotes: 6