This week's book giveaway is in the OCMJEA forum.
We're giving away four copies of OCM Java EE 6 Enterprise Architect Exam Guide and have Paul Allen & Joseph Bambara on-line!
See this thread for details.
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


Win a copy of OCM Java EE 6 Enterprise Architect Exam Guide this week in the OCMJEA forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Sort/Search comparator" Watch "Sort/Search comparator" New topic
Author

Sort/Search comparator

Henrique Boreg
Greenhorn

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.
Thanks.


"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
Marshal

Joined: Jul 08, 2003
Posts: 24183
    
  34

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
Greenhorn

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.

Thanks.
 
 
subject: Sort/Search comparator