Ordering enum values

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

    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 list = Arrays.asList(TestEnum.values());
            System.err.println(list);
            Collections.sort(list, new Comparator() {
                @Override
                public int compare(TestEnum o1, TestEnum o2) {
                    return o1.getValue1() - o2.getValue1();
                }
            });
            System.err.println(list);
            Collections.sort(list, new Comparator() {
                @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]

提交回复
热议问题