您可以根据需要在枚举中放置任意数量的比较器,请参见以下示例:
import java.util.Comparator;
public enum Day {
MONDAY(1, 3),
TUESDAY(2, 6),
WEDNESDAY(3, 5),
THURSDAY(4, 4),
FRIDAY(5, 2),
SATURDAY(6, 1),
SUNDAY(0, 0);
private final int calendarPosition;
private final int workLevel;
Day(int position, int level) {
calendarPosition = position;
workLevel = level;
}
int getCalendarPosition(){ return calendarPosition; }
int getWorkLevel() { return workLevel; }
public static Comparator<Day> calendarPositionComparator = new Comparator<Day>() {
public int compare(Day d1, Day d2) {
return d1.getCalendarPosition() - d2.getCalendarPosition();
}
};
public static Comparator<Day> workLevelComparator = new Comparator<Day>() {
public int compare(Day d1, Day d2) {
// descending order, harder first
return d2.getWorkLevel() - d1.getWorkLevel();
}
};
}
要查看比较器的运行情况:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class EnumDayTest
{
public static void main (String[] args) {
List<Day> allDays = Arrays.asList(Day.values());
System.out.println("===\nListing days in order of calendar position:");
Collections.sort(allDays, Day.calendarPositionComparator);
showItems(allDays);
System.out.println("===\nListing days in order of work level:");
Collections.sort(allDays, Day.workLevelComparator);
showItems(allDays);
}
public static void showItems(List<Day> days) {
for (Day day : days) {
System.out.println(day.name());
}
}
}