在Java中存储国家/地区代码、名称和Continent的最佳方式是使用Java的内置数据结构,如HashMap和Enum。
首先,创建一个枚举类来表示Continent:
public enum Continent {
ASIA,
EUROPE,
AFRICA,
NORTH_AMERICA,
SOUTH_AMERICA,
AUSTRALIA_OCEANIA
}
接下来,创建一个Country类来存储国家/地区代码、名称和Continent:
public class Country {
private String code;
private String name;
private Continent continent;
public Country(String code, String name, Continent continent) {
this.code = code;
this.name = name;
this.continent = continent;
}
public String getCode() {
return code;
}
public String getName() {
return name;
}
public Continent getContinent() {
return continent;
}
}
然后,创建一个HashMap来存储Country对象:
import java.util.HashMap;
public class CountryRepository {
private static HashMap<String, Country> countries = new HashMap<>();
public static void addCountry(Country country) {
countries.put(country.getCode(), country);
}
public static Country getCountry(String code) {
return countries.get(code);
}
}
现在,您可以使用CountryRepository类的addCountry方法添加国家/地区,并使用getCountry方法获取国家/地区信息。例如:
CountryRepository.addCountry(new Country("CN", "China", Continent.ASIA));
CountryRepository.addCountry(new Country("US", "United States", Continent.NORTH_AMERICA));
Country china = CountryRepository.getCountry("CN");
System.out.println("Code: " + china.getCode() + ", Name: " + china.getName() + ", Continent: " + china.getContinent());
这种方法允许您轻松地存储、检索和管理国家/地区代码、名称和Continent。
领取专属 10元无门槛券
手把手带您无忧上云