if-elseまたはスイッチの構造を見て悪いのJavaの代替

pobu:

見て悪いのif-elseまたはスイッチの構造を置き換えるために、文字列の翻訳を実現するための近代的な方法を探して:

if ("UK".equals(country)) 
     name = "United Kingdom";
  if ("GE".equals(country))
     name = "Germany";
  if ("FR".equals(country))
     name = "France";
  if ("IT".equals(country))
     name = "Italy";
  [...]

若しくは

switch (country) {
      case "UK": name = "United Kingdom"; break;
      case "GE": name = "Germany" break;
      case "FR": name = "France"; break;
      case "IT": name = "Italy" break;
  [...]
私fauzanメートル:

あなたは、単にjava.util.Mapを使用することができます。
静的な国の変数を作成します。

private static final String UK = "UK";
private static final String GE = "GE";
private static final String FR = "FR";
private static final String IT = "IT";

private static final Map<String, String> COUNTRIES;
static {
    final Map<String, String> countries = new HashMap<>();
    countries.put(UK, "United Kingdom");
    countries.put(GE, "Germany");
    countries.put(FR, "France");
    countries.put(IT, "Italy");
    COUNTRIES = Collections.unmodifiableMap(countries);
}

その後、国の名前を取得するにはjava.util.Mapから「取得」プロパティを使用することができます

System.out.println(COUNTRIES.get(UK));
System.out.println(COUNTRIES.get(GE));
System.out.println(COUNTRIES.get(FR));
System.out.println(COUNTRIES.get(IT));

おすすめ

転載: http://43.154.161.224:23101/article/api/json?id=164838&siteId=1