首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

在Java中存储国家/地区代码,名称和Continent的最佳方式

在Java中存储国家/地区代码、名称和Continent的最佳方式是使用Java的内置数据结构,如HashMap和Enum。

首先,创建一个枚举类来表示Continent:

代码语言:java
复制
public enum Continent {
    ASIA,
    EUROPE,
    AFRICA,
    NORTH_AMERICA,
    SOUTH_AMERICA,
    AUSTRALIA_OCEANIA
}

接下来,创建一个Country类来存储国家/地区代码、名称和Continent:

代码语言:java
复制
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对象:

代码语言:java
复制
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方法获取国家/地区信息。例如:

代码语言:java
复制
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。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

领券