Ordering enum values

comparable, enums, java

Solution

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.

Problem

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.

Original source