首页
学习
活动
专区
工具
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。

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

相关·内容

6分33秒

048.go的空接口

14分25秒

062_第六章_Flink中的时间和窗口(二)_水位线(三)_水位线在代码中的生成(一)

8分48秒

063_第六章_Flink中的时间和窗口(二)_水位线(三)_水位线在代码中的生成(二)

1分19秒

020-MyBatis教程-动态代理使用例子

14分15秒

021-MyBatis教程-parameterType使用

3分49秒

022-MyBatis教程-传参-一个简单类型

7分8秒

023-MyBatis教程-MyBatis是封装的jdbc操作

8分36秒

024-MyBatis教程-命名参数

15分31秒

025-MyBatis教程-使用对象传参

6分21秒

026-MyBatis教程-按位置传参

6分44秒

027-MyBatis教程-Map传参

15分6秒

028-MyBatis教程-两个占位符比较

领券