我想知道是否有任何方法可以对不同类的枚举进行排序。例如,如果我有一组固定的化学物质,它们以不同的方式与其他化学物质反应,有些很强烈,有些很弱。我基本上希望能够根据化学物质的不同来改变它们的排列顺序(即根据类的不同)。我确实知道我应该使用比较,但我不确定如何做到这一点。如果我说得不够清楚,请留下评论,我会进一步解释。
谢谢。
public static enum Chem {
H2SO4, 2KNO3, H20, NaCl, NO2
};所以我有一个看起来像那样的东西,我已经知道每种化学物质会如何与其他一些化学物质反应。我只是想根据化学物质的反应来安排化学物质。这差不多就是我的全部了。
发布于 2012-05-06 06:57:52
实现不同的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.发布于 2012-05-06 07:00:28
下面的示例向您展示了根据不同条件排序的枚举的相同值:
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);
}
}输出为
A,B,C C,B,A
发布于 2012-05-06 06:58:27
假设你有一个元素的枚举:
enum Elements {Oxygen, Hydrogen, Gold}如果您想按给定的顺序对它们进行排序,那么我可以这样做:
Elements[] myElements = Elements.values();
Arrays.sort(myElements, new ElementComparator());其中,ElementComparator可以是这样的:
public class ElementComparator implements java.util.Comparator<Elements> {
public int compare(Elements left, Elements right){
return right.compareTo(left); //use your criteria here
}
}在你的问题中,排序标准的性质并不清楚。看起来像是和化学反应有关的东西。我认为在给定化学反应的情况下,应该在Comparator中使用标准来确定哪个枚举元素比另一个元素大。
https://stackoverflow.com/questions/10466606
复制相似问题