Est*_*ter 4 java enums comparable
我想知道是否有任何方式为不同的类订购枚举.例如,如果我有一组固定的化学物质,它们以不同的方式与其他化学物质发生反应,有些是强烈的,有些是弱的.我基本上希望能够根据组应该响应的化学物质(即取决于类别)来切换它们的排列顺序.我知道我应该使用Comparable,但我不知道该怎么做.如果我不够清楚,请发表评论,我会进一步解释.
谢谢.
public static enum Chem {
H2SO4, 2KNO3, H20, NaCl, NO2
};
Run Code Online (Sandbox Code Playgroud)
所以我有一些看起来像这样的东西,我已经知道每种化学物质会如何与其他化学物质发生反应.我只是想根据它会与之反应的化学物质来安排Chems.这就是我所拥有的一切.
Mat*_*der 10
实现不同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.
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
18400 次 |
| 最近记录: |