Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sort/Search comparator

 
Henrique Boreg
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24211
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Henrique Boreg
Greenhorn
Posts: 23
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic