简体   繁体   English

用Java中的enum切换语句

[英]Switch statement with enum in Java

I hope someone can direct me to the right direction. 我希望有人可以指引我正确的方向。

I have the below code in enum with department names and their codes. 我在带有部门名称及其代码的枚举中包含以下代码。 I want to be able to print the departments' full names with their descriptions on the screen. 我希望能够在屏幕上打印部门的全名及其描述。 I want to accomplish that by using a switch statement, but I am unsure where to place the switch statement. 我想通过使用switch语句来实现这一点,但是我不确定将switch语句放在何处。

enum DepartmentName {
     FINANCE        ("FIN")
   , SALES          ("SAL")
   , PAYROLL        ("PYR")
   , LOGISTIC       ("LGT")
   ;

    private final String department;

    DepartmentName(String abbr) {
        department = abbr;
    }

    public String getDepartmentCode() {return department;}

    @Override
    public String toString() {
        return "The department name is " + getDepartmentCode();
    }
}

Any help is appreciated. 任何帮助表示赞赏。

I want to be able to print the departments' full names with their descriptions on the screen. 我希望能够在屏幕上打印部门的全名及其描述。

You need to associate the full name with each enum value. 您需要将全名与每个enum值相关联。 The simplest way of doing it is to add a description member to the enum : 最简单的方法是将description成员添加到enum

enum DepartmentName {
     FINANCE        ("FIN", "Finance")
   , SALES          ("SAL", "Sales")
   , PAYROLL        ("PYR", "Payroll")
   , LOGISTIC       ("LGT", "Logistic")
   ;

    private final String department;
    private final String description;

    DepartmentName(String abbr, String full) {
        department = abbr;
        description = full;
    }

    public String getDepartmentCode() {return department;}

    public String getDescription() {return description;}

    @Override
    public String toString() {
        return "The department name is " + getDepartmentCode();
    }
}

I want to accomplish that by using a switch statement 我想通过使用switch语句来实现

That would be a wrong way of doing that, because the association with the name would be external to the enum (ie no longer be encapsulated). 这将是错误的方法,因为与名称的关联将在enum外部(即不再被封装)。 The consequence of this is that each time you add a new enum member, all your switches that depend on that enum would need to change. 这样的结果是,每次添加新的enum成员时,所有依赖于该enum switches都需要更改。 Moreover, the compiler would not be able to help you catch places where you missed the new enum value. 此外,编译器将无法帮助您找到错过新enum值的地方。

To String should be following: To String应该如下:

public String toString() {
    switch (this) {
        case FINANCE:
            return "finance";
        case SALES:
            return "sales";
        case PAYROLL:
            return "payroll";
        ... // and so on
    }
    return this.name();
}

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

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