Ordering enum values

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

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

    Comparator comparator1 = new Comparator() {
    
      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.
    

提交回复
热议问题