Ordering enum values

2019-02-17 23:52发布

问题:

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 chemicals, some strongly, some weakly. I basically want to be able to switch up the order in which they are arranged depending on the chemical the group is supposed to react to(i.e depending on the class.). I do know that I am supposed to use Comparable but I am not sure how to do it. If I am not clear enough, leave a comment and I will explain further.

Thanks.

public static enum Chem {
    H2SO4, 2KNO3, H20, NaCl, NO2
};

So I have something that looks like that and I already know how each chemical would react to some other chemicals. I simply want to arrange the Chems based on the chemical it would be reacting with. That's pretty much all I have.

回答1:

Implement different Comparator's ( see http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html )

Comparator comparator1 = new Comparator<MyEnum>() {

  public int compare(MyEnum e1, MyEnum e2) {
     //your magic happens here
     if (...)
       return -1;
     else if (...)
       return 1;

     return 0;
  }
};

//and others for different ways of comparing them

//Then use one of them:
MyEnum[] allChemicals = MyEnum.values();
Arrays.sort(allChemicals, comparator1); //this is how you sort them according to the sort critiera in comparator1.


回答2:

Here is an example showing you the same values of the enum sorted according to different criteria:

import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class SortEnum {

    public enum TestEnum {
        A(1, 2), B(5, 1), C(3, 0);
        private int value1;
        private int value2;

        private TestEnum(int value1, int value2) {
            this.value1 = value1;
            this.value2 = value2;
        }

        public int getValue1() {
            return value1;
        }

        public int getValue2() {
            return value2;
        }
    }

    public static void main(String[] args) {
        List<TestEnum> list = Arrays.asList(TestEnum.values());
        System.err.println(list);
        Collections.sort(list, new Comparator<TestEnum>() {
            @Override
            public int compare(TestEnum o1, TestEnum o2) {
                return o1.getValue1() - o2.getValue1();
            }
        });
        System.err.println(list);
        Collections.sort(list, new Comparator<TestEnum>() {
            @Override
            public int compare(TestEnum o1, TestEnum o2) {
                return o1.getValue2() - o2.getValue2();
            }
        });
        System.err.println(list);
    }
}

OUTPUT is

[A, B, C] [A, C, B] [C, B, A]



回答3:

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

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


回答4:

Suppose you have an enum of elements:

enum Elements {Oxygen, Hydrogen, Gold}

and you would like to sort them in a given order, then I can do:

Elements[] myElements = Elements.values();
Arrays.sort(myElements, new ElementComparator());

where ElementComparator can be something like:

public class ElementComparator implements java.util.Comparator<Elements> {
    public int compare(Elements left, Elements right){
        return right.compareTo(left); //use your criteria here
    }
}

The nature of the ordering criteria is not clear in your question. It seems like it's about something related to chemical reactions. I suppose that criteria should go in the Comparator to decide which enum element is bigger than the other given a chemical reaction.



回答5:

You mean the actual objects representing your chemicals are enums? That sooooounds like an odd implementation if I may say: enums are really more suited to 'properties' of something.

But anyway... if you really want to represent them as enums and then sort them, I would suggest implemeting a Comparator that can sort enums of your particular type, then in its compare() method, make the appropriate comparison, e.g.:

Comparator<Chemical> comp = new Comparator<Chemical>() {
    public int compare(Chemical o1, Chemical o2) {
        if (o1.reactivity() > o2.reactivity()) {
          return 1;
        } else if (o1.reactivity() < o2.reactivity()) {
          return -1;
        } else {
        return integer depending on whatever else you want to order by...
        }
    }
};

Then you can pass this comparator in to the sort method, ordered collection constructor etc involved.

You can extend your enum subclass to include whatever extra methods, e.g. reactivity(), that you require.