请在下面找到我的枚举类:
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/