【发布时间】:2015-10-17 10:43:23
【问题描述】:
我有以下代码,可以让我获得所有国家/地区名称的列表:D
private List<String> countriesList = new ArrayList<String>();
public List<String> getCountriesList() {
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
Locale obj = new Locale("", countryCode);
countriesList.add(obj.getDisplayCountry(Locale.ENGLISH));
}
Collections.sort(countriesList);
countriesList.add(0, "International");
System.out.println(countriesList);
return countriesList;
}
我现在需要做的是将所有这些国家映射到一个 ID 号。
ID 号将从:32000006 开始,到 32000260 结束
我不确定我需要做什么来映射数字。我知道基本上我会通过一个方法传递一个 int,然后该方法将匹配传递给该方法的 ID,然后我需要它返回国家名称。
我不知道该怎么做,但我注意到一个问题是 ID 32000008 属于这个国家:奥兰群岛,但由于它有一个奇怪的 A,它在我的列表末尾。我仍然需要它来拥有 ID 32000008。
如果有人知道我需要对我的方法做些什么来完成这件事,我将不胜感激。
谢谢:)
更新 我尝试使用 HashMap 并得到以下代码:
public class test{
public static void main (String[] args) throws java.lang.Exception
{
getCountriesList();
}
private static HashMap<Integer,String> countriesList = new HashMap<Integer,String>();
public static void getCountriesList() {
String[] locales = Locale.getISOCountries();
for (String countryCode : locales) {
int i = 32000007;
Locale obj = new Locale("", countryCode);
countriesList.put(i,obj.getDisplayCountry(Locale.ENGLISH));
i++;
}
countriesList.put(32000006,"International");
System.out.println(countriesList);
}
}
哪些输出: {32000006=国际,32000007=津巴布韦}
任何想法为什么它不起作用?
【问题讨论】:
-
你知道Java中的HashMaps吗?
-
@MB_CE 不是真的
-
所以,HashMap 也是 Java 集合的一部分,它允许您使用键添加数据,例如
hashMap.put(key,value),同样您也可以通过键获取数据。所以在HashMap中存储国家数据时可以使用ID作为key,之后通过ID获取。看看他们docs.oracle.com/javase/7/docs/api/java/util/HashMap.html -
@MB_CE 查看我的编辑 :)
标签: java list dictionary iso