Java alternative de la recherche si mauvaise-ELSE ou constructions commutateur

pobu:

Vous recherchez de façon moderne pour réaliser la traduction chaîne pour remplacer la recherche si mauvaise-ELSE ou constructions commutateur:

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";
  [...]

ou

switch (country) {
      case "UK": name = "United Kingdom"; break;
      case "GE": name = "Germany" break;
      case "FR": name = "France"; break;
      case "IT": name = "Italy" break;
  [...]
m me Fauzan:

Vous pouvez simplement utiliser java.util.Map.
Créer une variable de pays statique.

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);
}

puis peut utiliser la propriété « get » de java.util.Map pour obtenir le nom du pays

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

Je suppose que tu aimes

Origine http://43.154.161.224:23101/article/api/json?id=164922&siteId=1
conseillé
Classement