File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Beginning Java and the fly likes Sort/Search comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sort/Search comparator" Watch "Sort/Search comparator" New topic

Sort/Search comparator

Henrique Boreg

Joined: Aug 11, 2005
Posts: 23
I'm trying to implement a simple scheduling system composed of 2 classes: Appointment and Agenda having the following fields:

I want to sort the list of appointments in agenda using their descriptions, so I have the following Comparator (which works well):

The thing is that I want to implement a search by keywords, so it would be used like: searchAppointmentsByKeyword(list_of_appointments, keyword), with only one keyword at a time (a String object).
Since the sort and search methods work on different fields, how would I merge them so they could work ok?..I've tried writing 2 comparator, one for search and another one for sort but their working well is apparently based on pure luck so it didn't convince me...which makes sense for them not to work since the sort method sorts them in a different way then needed for a later usage of search.

Any help is appreciated.

"I wrote an all-Java OS in 1998 but can't be sure if or how it works... it's still booting"
Ernest Friedman-Hill
author and iconoclast

Joined: Jul 08, 2003
Posts: 24199

First of all, I challenge your assertion that this Comparator works well. Look at this line:

if(app1.getDescription().charAt(0) < app1.getDescription().charAt(0)) return -1;

That test will never be true.

Now, as to your question: I'm not sure what search methods you're talking about, but it's likely that they don't apply. Because your appointments will have multiple keywords, they can't be sorted by keyword, and so the binarySearch() methods can't work. You can implement the loops yourself and do a linear search -- i.e.,

If you want to make this faster, you could have a Map<String, List<Appointment>>, where the keys are the keywords. Maintaining this might be tricky, but finding appointments by keyword would be fast.

[Jess in Action][AskingGoodQuestions]
Henrique Boreg

Joined: Aug 11, 2005
Posts: 23
That was just my bad copying/pasting the code...
I rewrote a simple search myself and it works ok now since it doesn't need to perform a sorting of the objects before searching.

I agree. Here's the link:
subject: Sort/Search comparator
jQuery in Action, 3rd edition