The JodaTime DateTime
class implements the Comparable
interface itself, so you don't need to implement a Comparator
.
Rather, use Collections.binarySearch
with just 2 arguments: list
and key
.
There may be a mistake in your implementation of the Comparator
, and if you post it, we may be able to identify it.
However your question was whether it is possible to use DateTime
in a binary search, and the answer is: yes. Let the built-in DateTime.compareTo
function (implemented in superclass AbstractInstant
) do its work.
Addendum
As your code shows, you're not directly comparing DateTime
objects, but you're comparing Holiday
objects using your HolidayComparator
.
The Javadoc of the class Comparator
describes what the compare
method should return:
Compares its two arguments for order. Returns a negative integer, zero, or a positive integer as the first argument is less than, equal to, or greater than the second.
Your method only returns 0 if the objects are equal and -1 if they are not. That's incorrect and it confuses the Collections.binarySearch
method.
Try this instead:
class HolidayComparator implements Comparator<Holiday> {
public int compare(Holiday h1, Holiday h2) {
return h1.getDate().compareTo(h2.getDate());
}
}
That is the best way to do it, because it re-uses existing code in JodaTime and it doesn't make you depend on its internals. To make it nicer, you should add checks for null
though, if you can ever have a null
value in your list of Holidays, or if you ever have a null
date in one of the Holiday
objects.
If you want to look more to the internals: the compareTo method in DateTime
(superclass AbstractInstant
) actually compares the result of the method getMillis()
, so an alternative way of writing this is:
public int compare(Holiday h1, Holiday h2) {
long millis1 = h1.getDate().getMillis();
long millis2 = h2.getDate().getMillis();
return Long.compare(millis1, millis2);
}
And Long.compare
is implemented as:
Long.compare
:
public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}