简体   繁体   English

在If条件下匹配Java中的枚举字符串

[英]Matching enum Strings in Java in If conditions

I have an enum: 我有一个枚举:

public enum Status{
   A("A"),
   B("B"),
   C("C"),
   D("D"),
   E("E")
}

A,B,C are in one category and D&E are a different category. A,B,C属于一个类别,D&E属于不同类别。 Now when I get a string, I want to decide which category it falls in. Basically, 现在当我得到一个字符串时,我想决定它属于哪个类别。基本上,

String s;
if   s.equals( Status.A.toString()) || s.equals(Status.B.toString()) || s.equals( Status.C.toString()) 
            return 1; 

        else return 2;

Now, this is manageable with 5 letters. 现在,这可以通过5个字母来管理。 If I have 26 letters, the number of if conditions will be unmanageable. 如果我有26个字母,if条件的数量将无法管理。 Is there a better way to write this? 有没有更好的方法来写这个?

Rather than deciding the category in the code, store it in the enum itself. 而不是在代码中确定类别,而是将其存储在enum本身中。 You are not limited to a single stored attribute; 您不仅限于单个存储属性; you can have as many as you wish. 你可以拥有任意多的人。

Change the constructor to take the category in addition to the letter, and store it in the enum : 更改构造函数以获取除字母之外的类别,并将其存储在enum

public enum Status {
    A("A", 1),
    B("B", 1),
    C("C", 1),
    D("D", 2),
    E("E", 2);
    private String name;
    private int category;
    public String getName() { return name; }
    public int getCategory() { return category; }
    Status(String name, int category) {
        this.name = name;
        this.category = category;
    }
}

Now it is very clear which enum belongs to what category, because categories are assigned declaratively rather than algorithmically. 现在很清楚哪个枚举属于哪个类别,因为类别是以声明方式而不是算法方式分配的。

How about you maintain a list of enums per category and then compare your string with the enums in a category list? 如何维护每个类别的枚举列表,然后将您的字符串与类别列表中的枚举进行比较? See the following example. 请参阅以下示例。

    List<Status> category1 = new ArrayList<Status>();
    category1.add(Status.A);
    category1.add(Status.B);
    category1.add(Status.C);
    List<Status> category2 = new ArrayList<Status>();
    category2.add(Status.D);
    category2.add(Status.E);

    for(Status e : category1) {
        if(s.equals(e.toString()))
            return true;
    }

    for(Status e : category2) {
        if(s.equals(e.toString()))
            return true;
    }

    return false;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM