aspose file tools
The moose likes Beginning Java and the fly likes Sorting results using custom comparator Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Reply Bookmark "Sorting results using custom comparator" Watch "Sorting results using custom comparator" New topic
Author

Sorting results using custom comparator

Eshwar Prasad
Ranch Hand

Joined: Mar 21, 2008
Posts: 191

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
Marshal

Joined: Jul 08, 2003
Posts: 24061
    
  13

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


[Jess in Action][AskingGoodQuestions]
 
I agree. Here's the link: http://ej-technologies/jprofiler - if it wasn't for jprofiler, we would need to run our stuff on 16 servers instead of 3.
 
subject: Sorting results using custom comparator
 
Similar Threads
need help with Arrays.sort() and compareTo()
why there are two interfaces in java for sorting Purpose?
comparator and comparable interfaces
Sorting java.lang.objects
Comparable and comparator interface