java 排序枚举值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10466606/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 01:10:18  来源:igfitidea点击:

Ordering enum values

javaenumscomparable

提问by Ester

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.

我想知道是否有任何方法可以为不同的类订购枚举。例如,如果我有一组固定的化学物质,它们以不同的方式与其他化学物质发生反应,有些强烈,有些反应较弱。我基本上希望能够根据组应该反应的化学物质(即取决于类)来改变它们的排列顺序。我确实知道我应该使用 Comparable,但我不知道该怎么做。如果我不够清楚,请发表评论,我会进一步解释。

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.

所以我有一些看起来像这样的东西,而且我已经知道每种化学物质会如何与其他一些化学物质发生反应。我只是想根据它会发生反应的化学物质来安排化学物质。这几乎就是我所拥有的。

回答by Mattias Isegran Bergander

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

实现不同Comparator的(见http://docs.oracle.com/javase/6/docs/api/java/util/Comparator.html

Comparator comparator1 = new Comparator<MyEnum>() {

  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.

回答by Guillaume Polet

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

[A, B, C] [A, C, B] [C, B, A]

回答by Edwin Dalorzo

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 ElementComparatorcan be something like:

哪里ElementComparator可以是这样的:

public class ElementComparator implements java.util.Comparator<Elements> {
    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 Comparatorto decide which enum element is bigger than the other given a chemical reaction.

您的问题中订购标准的性质不清楚。好像跟化学反应有关。我想标准应该在Comparator决定哪个枚举元素大于另一个给定化学反应时。

回答by MaxZoom

You can put as many comparators in the enum as you like, see below example:

您可以根据需要在枚举中放置任意数量的比较器,请参见以下示例:

import java.util.Comparator;

public enum Day {
    MONDAY(1, 3),
    TUESDAY(2, 6),
    WEDNESDAY(3, 5),
    THURSDAY(4, 4),
    FRIDAY(5, 2),
    SATURDAY(6, 1),
    SUNDAY(0, 0);

    private final int calendarPosition;
    private final int workLevel;

    Day(int position, int level) {
      calendarPosition = position;
      workLevel = level;
    }

    int getCalendarPosition(){ return calendarPosition; }  
    int getWorkLevel() { return workLevel;  }

    public static Comparator<Day> calendarPositionComparator = new Comparator<Day>() {
      public int compare(Day d1, Day d2) {
        return d1.getCalendarPosition() - d2.getCalendarPosition();
      }
    };

    public static Comparator<Day> workLevelComparator = new Comparator<Day>() {
      public int compare(Day d1, Day d2) {
        // descending order, harder first
        return d2.getWorkLevel() - d1.getWorkLevel();
      }
    };
}

To see comparators in action:

要查看操作中的比较器:

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class EnumDayTest
{
  public static void main (String[] args) {
     List<Day> allDays = Arrays.asList(Day.values());
     System.out.println("===\nListing days in order of calendar position:");
     Collections.sort(allDays, Day.calendarPositionComparator);
     showItems(allDays);
     System.out.println("===\nListing days in order of work level:");
     Collections.sort(allDays, Day.workLevelComparator);
     showItems(allDays);
  }

  public static void showItems(List<Day> days) {
    for (Day day : days) {
      System.out.println(day.name());
    }
  }
}

回答by Neil Coffey

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

但无论如何......如果你真的想将它们表示为枚举然后对它们进行排序,我会建议实现一个可以对你的特定类型的枚举进行排序的比较器,然后在它的 compare() 方法中,进行适当的比较,例如:

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

您可以扩展您的 enum 子类以包含您需要的任何额外方法,例如 reactivity()。