Ordering enum values

后端 未结 5 1515
太阳男子
太阳男子 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:30

    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 {
        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.

提交回复
热议问题