Best way to store Country codes, names, and Continent in Java

后端 未结 5 992
Happy的楠姐
Happy的楠姐 2021-02-03 13:30

I want to have a List or Array of some sort, storing this information about each country:

  • 2 letter code
  • Country name such as Br
5条回答
  •  一个人的身影
    2021-02-03 14:04

    Just make an enum called Country. Java enums can have properties, so there's your country code and name. For the continent, you pobably want another enum.

    public enum Continent
    {
        AFRICA, ANTARCTICA, ASIA, AUSTRALIA, EUROPE, NORTH_AMERICA, SOUTH_AMERICA
    }
    
    public enum Country
    {
        ALBANIA("AL", "Albania", Continent.EUROPE),
        ANDORRA("AN", "Andorra", Continent.EUROPE),
        ...
    
        private String code;
        private String name;
        private Continent continent;
    
        // get methods go here    
    
        private Country(String code, String name, Continent continent)
        {
            this.code = code;
            this.name = name;
            this.continent = continent;
        }
    }
    

    As for storing and access, one Map for each of the fields you'll be searching for, keyed on that that field, would be the standard solution. Since you have multiple values for the continent, you'll either have to use a Map>, or a Multimap implementation e.g. from Apache commons.

提交回复
热议问题