java - How to get a certain enum instance when we are given only 1 value of its parameters? -
please find enum class below:
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"), // , 1 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
now if given country name i.e. label, how corresponding enum instance? if given "andorra", want ad
.
i cache relations within map keys labels , values corresponding countrycode insances. way, iterate on countrycode instances once instead of each time getbylabel()
method gets called.
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>(); (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); } }
then, call:
countrycode countrycode = countrycode.getbylabel("andorra");
Comments
Post a Comment