Reputation: 8276
public int compareTo(Object obj){
Books bk = (Books) bk;
return this.id - obj.id;
}
my code works fine when id
is an Integer
and when is a positive value. Is it possible for id
to be a negative value? How to change the code for that?
Upvotes: 0
Views: 89
Reputation: 11779
When you override compareTo
you get to define the answer to these questions. It completely depends on your program whether it's possible for id
to be a negative value. The question you have to ask yourself is "what does it mean for one book to be 'larger' (or smaller) than another one?". If the answer is just which ever has the larger id is a larger Book, then your implementation is fine, except for one minor mistake:
public int compareTo(Object obj){
Books bk = (Books) obj;
return this.id - bk.id;
}
Upvotes: 1
Reputation: 8276
I made it work :D
return (this.id > bk.id ) ? -1: (this.id < bk.id) ? 1:0 ;
this works how I wanted it but thanks for your reply
Upvotes: 0
Reputation: 24780
You must be able to return a negative value. From the Comparable
specification, if
a.compareTo(b) > 0
then
b.compareTo(a) < 0
Otherwise you could not use compareTo()
to stablish an order
Upvotes: 0
Reputation: 500267
The following is perhaps the easiest way to implement it:
public int compareTo(Object obj) {
Books bk = (Books)obj;
return Integer.compare(this.id, bk.id);
}
Your current version is almost correct, except that it is susceptible to integer overflow.
Upvotes: 2