• Post Reply Bookmark Topic Watch Topic
  • New Topic

Sorting results using custom comparator  RSS feed

 
Skanda Raman
Ranch Hand
Posts: 205
Spring
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I have a requirement to sort the results of book retrieved from the database. The resultset contain 5 different columns like A B C D E. I implemented custom comparator to sort the values of column A as below



Sorting is happening perfectly. My question is if i need to provide user a option to sort other four columns, should i write 4 different classes implementing Comparator.

Also, as compareTo method is used here, do i need to override toString() , equals and hashCode method in my Book Class.

Please excuse me if it is very basic question. Kindly let me know your suggestions.
 
Ernest Friedman-Hill
author and iconoclast
Sheriff
Posts: 24217
38
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can write four different comparator classes, or you can use one comparator that does different things based on a constructor argument. Either way.

You really need to consider overriding equals() and hashCode() if you intend to put instances of a class into a Collection of any kind. This class seems to qualify, so I'd say "yes".
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!