订购枚举值 [英] Ordering enum values

查看:212
本文介绍了订购枚举值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有任何方式为不同的类订购枚举。例如,我有一组固定的化学物质,其他化学物质的反应方式不同,有些弱化了。我基本上想要根据组应该对其进行反应的化学物质(即根据类别)来切换排列顺序。我知道我应该使用可比较,但我不知道该怎么做。如果我不够清楚,请发表评论,我会进一步解释。



谢谢。

  public static enum Chem {
H2SO4,2KNO3,H20,NaCl,NO2
};

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

解决方案

实现不同的比较器(见http://docs.oracle.com/javase/6/docs/api/java/util/Comparator比较器比较器1 =新的比较器< MyEnum>(){

public int compare(MyEnum e1,MyEnum e2){
//你的魔法发生在这里
if(...)
return -1;
else if(...)
return 1;

return 0;
}
};

//和其他用于比较他们的不同方式

//然后使用其中之一:
MyEnum [] allChemicals = MyEnum.values();
Arrays.sort(allChemicals,comparator1); //这是你如何根据在比较器1中的排序critiera进行排序。


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.

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.

解决方案

Implement different Comparator's ( see 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.

这篇关于订购枚举值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆