Ordering enum values

后端 未结 5 1526
太阳男子
太阳男子 2021-01-14 03:05

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

5条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-14 03:48

    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());
        }
      }
    }
    

提交回复
热议问题