如何在Java的Switch的Case值中添加字符串数组项?

Anu*_*rag 0 java arrays string switch-statement

我们知道,从Java 7开始,Switch的表达式可以是String。因此,我正在开发一个应用程序,其中,当用户选择类别时,将根据类别值为他/她分配相关部门。这是代码:

    public class Selector {
    ///String array to save the departments
    private final static String[] DEPTS = {
            "A",
            "B",
            "C",
            "D"
    };

    //String array for the categories
    private final static String[] CATEGORY = {
            "Wind",
            "Air",
            "Fire",
            "Cloud",
            "River",
            "Tree",
            "Abc",
            "Def"
    };

    //return the department when user selects a particular category item from above
    public static String setDepartment(String category) {
        switch(category){
            case "Wind":
                return DEPTS[0];
            case "Air":
                return DEPTS[1];
            case "Fire": case "Cloud": case "River":
                return DEPTS[2];
            case "Tree": case "Abc": case "Def":
                return DEPTS[3];            
        }
        return null;
    }
}
Run Code Online (Sandbox Code Playgroud)

所以我在考虑如何使用部门的数组索引返回部门项目,是否可以在case值中使用相同的内容,例如,

case CATEGORY[0]: case CATEGORY[1]: 
     return DEPTS[2];
Run Code Online (Sandbox Code Playgroud)

如果类别项包含的字符串大于大小写,则导致写的时间过长。如果Java不允许这样做,那么您可以提出其他建议,以免我的代码繁琐吗?谢谢。

小智 6

您为什么不使用枚举来做到这一点。

public class Selector {

  private enum DepartmentCategory = {
    Wind("A"),
    Air("B"),
    Fire("C"),
    Cloud("C"),
    River("C"),
    Tree("D"),
    Abc("D"),
    Def("E");

    private String department;

    DepartmentCategory(String department) {
      this.department = department;
    }
    public String getDepartment() {
      return department;
    }
  };
}
Run Code Online (Sandbox Code Playgroud)

现在,如果为您提供部门,则可以通过以下代码轻松获得类别。

String category = "Wind";
DepartmentCategory dc = DepartmentCategory.valueOf(category);
dc.getDepartment(); // Returns the department
Run Code Online (Sandbox Code Playgroud)