I’m using Collections.sort to sort a ArrayList of objects, and I want to see if there is a more efficient compareTo method for what I’m trying to do.
Here’s the method:
@Override
public int compareTo(Song s) {
if (runningTime > s.runningTime) {
return -1;
} else if (runningTime < s.runningTime) {
return 1;
}
int lastCmp = title.compareTo(s.title);
return (lastCmp != 0 ? lastCmp : composer.compareTo(s.composer));
}
If anyone could suggest a more efficient method (i.e. quicker runtime) I would be very grateful.
Just like MeBigFatGuy said, any improvement is insignificant, but I think you can still clean up the code a bit to reduce unnecessary if-else condition. My two cents.