Say I have a Song object like
public Song(){
String artist, title;
StringBuilder lyrics;
int rank;
}
Is it possible to have multiple compare methods that, depending on the collection used, sort by a particular field? This object already has a compare method for ordering based on the artist and title values, and I would like to be able to order based on the rank.
My current project requires us to run a search on the lyrics of the Song and return a high to low match list. I want to use a PriorityQueue to hold the matches based on rank value.
Normally I would simply create another object to hold the Song and the rank, but this project not only plugs into a GUI interface provided by the professor, which requires any results be passed in an Song[] array, but prints out the first ten values as Rank, Artist, Title.
I can use toArray() to convert the queue, but if I use it to store anything other than Song objects, it will throw an ArrayStoreException.
So is this possible, or do I have to modify the existing compare method to sort by integer value?
Most ordered collections have a constructor that takes a
Comparatoras an argument. Define a few static comparators in yourSongclass and then define things as follows:There are utility classes (e.g., Guava Ordering) that can help you build up other comparators from the basics.