Ordering enum values

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

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

    Comparator comp = new Comparator() {
        public int compare(Chemical o1, Chemical o2) {
            if (o1.reactivity() > o2.reactivity()) {
              return 1;
            } else if (o1.reactivity() < o2.reactivity()) {
              return -1;
            } else {
            return integer depending on whatever else you want to order by...
            }
        }
    };
    

    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.

提交回复
热议问题