I am currently working on a project that asks me to sort a collection of songs. I am using the solution presented in this question to accomplish this, while modifying it slightly:Sorting a collection of objects
import java.util.Comparator;
public class SongComparator implements Comparator<Song> {
public enum Order {
YEAR_SORT, RANK_SORT, ARTIST_SORT, TITLE_SORT
}
public Order sortingBy;
@Override
public int compare(Song song1, Song song2) {
switch (sortingBy) {
case YEAR_SORT:
return Integer.compare(song1.year, song2.year);
case RANK_SORT:
return Integer.compare(song1.rank, song2.rank);
case ARTIST_SORT:
return song1.artist.compareTo(song2.artist);
case TITLE_SORT:
return song1.title.compareTo(song2.title);
}
throw new RuntimeException(
"Practically unreachable code, can't be thrown");
}
public void setSortingBy(Order sortBy) {
this.sortingBy = sortingBy;
}
}
Example sort method:
public void sortTitle() {
SongComparator comparator = new SongComparator();
SongComparator.Order sortingBy = SongComparator.Order.TITLE_SORT;
Collections.sort(songs2, comparator);
}
I want to be able to change the sortingBy
variable when each respective sortField
method is run, so that way it will run the right compare method. However, the way that I'm defining it in the method is just making a new sortingBy
variable without changing the one in the SongComparator
class at all.