I have a list of holiday objects which include a jodatime DateTime field. This list is manually ordered from the earliest date to the latest date.
I would like to use a binary search to search for a match. I implemented a comparator, but the algorithm doesn't seem to go in the right direction. Are jodatime DateTimes not amenable to binary searches or is there something else I need to do get this working?
Note that I am using the Collections.binarySearch tool and following this example: http://java2novice.com/java-collections-and-util/collections/binary-search/
Here is the search output:
Date 1:
2015-02-16T00:00:00.000-08:00
Target date:
2014-12-25T00:00:00.000-08:00
no match
Date 1:
2016-10-10T00:00:00.000-07:00
Target date:
2014-12-25T00:00:00.000-08:00
no match
Date 1:
2017-03-31T00:00:00.000-07:00
Target date:
2014-12-25T00:00:00.000-08:00
no match
Date 1:
2017-10-12T00:00:00.000-07:00
Target date:
2014-12-25T00:00:00.000-08:00
no match
Date 1:
2017-11-23T00:00:00.000-08:00
Target date:
2014-12-25T00:00:00.000-08:00
no match
Date 1:
2017-11-24T00:00:00.000-08:00
Target date:
2014-12-25T00:00:00.000-08:00
no match
Date 1:
2017-12-25T00:00:00.000-08:00
Target date:
2014-12-25T00:00:00.000-08:00
no match
-71
Comparator:
class HolidayComparator implements Comparator<Holiday> {
public int compare(Holiday h1, Holiday h2) {
System.out.println("Date 1:");
System.out.println(h1.getDate());
System.out.println("Target date:");
System.out.println(h2.getDate());
if(h1.getDate().equals(h2.getDate())) {
return 0;
}
else {
System.out.println("no match");
return -1;
}
}
};
Adding some other classes:
public static List<Holiday> getAllHolidays() {
return allHolidays;
}
Holiday object:
public static class Holiday {
DateTime date;
String name;
Holiday(int i, int j, int k, String x) {
date = new DateTime (i, j, k, 0, 0);
name = x;
}
public DateTime getDate() {
return date;
}
}
List:
private static List<Holiday> allHolidays = Arrays.asList(new Holiday(2012, 12, 25, "Christmas 2012"), etc.)
Binary search:
int index = Collections.binarySearch(Holidays.getAllHolidays(), new Holidays.Holiday(2014, 12, 25, null));
Returns:
The method binarySearch(List<? extends Comparable<? super T>>, T) in the type Collections is not applicable for the arguments (List<Holidays.Holiday>, Holidays.Holiday)