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?
Method 2: Using comparator interface- Comparator interface is used to order the objects of a user-defined class. This interface is present in java. util package and contains 2 methods compare(Object obj1, Object obj2) and equals(Object element). Using a comparator, we can sort the elements based on data members.
This interface is found in java. lang package and contains only one method named compareTo(Object).
The Comparable interface defines the compareTo method used to compare objects. If a class implements the Comparable interface, objects created from that class can be sorted using Java's sorting algorithms.
The Java Comparable compareTo() method takes a single object as parameter and returns an int value. The int returned signal whether the object the compareTo() method is called on is larger than, equal to or smaller than the parameter object.
Use a Comparator.
Comparator<Song> rankOrder = new Comparator<Song>() {
public int compare(Song s1, Song e2) {
return s1.rank - s2.rank;
}
};
Collections.sort(songs, rankOrder);
See http://download.oracle.com/javase/tutorial/collections/interfaces/order.html
Most ordered collections have a constructor that takes a Comparator
as an argument. Define a few static comparators in your Song
class and then define things as follows:
Set<Song> allSongs = new TreeSet<Song>(Song.BY_TITLE);
PriorityQueue<Song> rankedSongs = new PriorityQueue<Song>(10, Song.BY_RANK);
There are utility classes (e.g., Guava Ordering) that can help you build up other comparators from the basics.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With