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.
Implement different
Comparator
's ( see http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html )Here is an example showing you the same values of the enum sorted according to different criteria:
OUTPUT is
You can put as many comparators in the enum as you like, see below example:
To see comparators in action:
Suppose you have an enum of elements:
and you would like to sort them in a given order, then I can do:
where
ElementComparator
can be something like: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.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.:
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.