java - 当我们只给出 1 个参数值时,如何获取某个枚举实例?

标签 java enums

请在下面找到我的枚举类:

public enum CountryCode //implements IEnum
{
AD("Andorra", "AND", "Europe", "South West Europe"),
AE("United Arab Emirates", "ARE", "Asia", "South West Asia"),
AF("Afghanistan", "AFG", "Asia", "South Asia"),
// and so one till Z

// attributes defined
private final String label;
private final String isoCode3;
private final String continent;
private final String region;

// countructor defined
private CountryCode(String label, String isoCode3, String continent, String region)
{
    this.label = label;
    this.isoCode3 = isoCode3;
    this.continent = continent;
    this.region = region;

}   // END CountryCode

} // END enum CountryCode

现在,如果我只得到国家/地区名称(即标签),那么我将如何获取其相应的枚举实例?因此,如果给定“Andorra”,我想要 AD

最佳答案

我会缓存 Map 中的关系,其中键是标签,值是相应的 CountryCode 实例。这样,您只需迭代一次 CountryCode 实例,而不是每次调用 getByLabel() 方法时。

public enum CountryCode {

    AD("Andorra", "AND", "Europe", "South West Europe"),
    AE("United Arab Emirates", "ARE", "Asia", "South West Asia"),
    AF("Afghanistan", "AFG", "Asia", "South Asia");

    private static final Map<String, CountryCode> BY_LABEL;
    static {
        Map<String, CountryCode> byLabel = new HashMap<String, CountryCode>();
        for (CountryCode countryCode : values()) {
            byLabel.put(countryCode.label, countryCode);
        }
        BY_LABEL = Collections.unmodifiableMap(byLabel);
    }

    private final String label;
    private final String isoCode3;
    private final String continent;
    private final String region;

    private CountryCode(String label, String isoCode3, String continent, String region) {
        this.label = label;
        this.isoCode3 = isoCode3;
        this.continent = continent;
        this.region = region;
    }

    public static CountryCode getByLabel(String label) {
        return BY_LABEL.get(label);
    }

}

然后,只需调用:

CountryCode countryCode = CountryCode.getByLabel("Andorra");

关于java - 当我们只给出 1 个参数值时,如何获取某个枚举实例?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22300820/

相关文章:

c# - 将 SSL 应用程序从 Java 移植到 C#

java - 返回枚举值而不调用 get 函数

java - jsp 未以正确格式传递 UTF-8 数据

java - 使用 String.replaceFirst(regexp, "$1") 获取匹配的子字符串时得到空字符串,正则表达式有什么问题?

java - 如何从 clojure 项目在 eclipse 中使用 java 项目

python - python 中的枚举有什么好的用例?

angular - typescript 中枚举声明中的方括号的含义是什么?

java - 没有接口(interface)使用spring DI是否正确

java - 如何使用策略或功能接口(interface)处理基于值(枚举)的多种选择?

c - 使用结构和枚举洗牌