I was wondering if there is any way of ordering enum for different classes. If for example, I have a fixed group of chemicals which react in different ways to other chemical
You can put as many comparators in the enum as you like, see below example:
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 calendarPositionComparator = new Comparator() {
public int compare(Day d1, Day d2) {
return d1.getCalendarPosition() - d2.getCalendarPosition();
}
};
public static Comparator workLevelComparator = new Comparator() {
public int compare(Day d1, Day d2) {
// descending order, harder first
return d2.getWorkLevel() - d1.getWorkLevel();
}
};
}
To see comparators in action:
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
public class EnumDayTest
{
public static void main (String[] args) {
List 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 days) {
for (Day day : days) {
System.out.println(day.name());
}
}
}