我遇到同样的问题,很多人似乎面临来自
PHP,缺乏一个体面和易于使用的关联阵列解决方案.
我已经在这里阅读了,基本上都建议使用HashMap,像这样Q:
Java associative-array
但是,我不认为所提到的解决方案可以解决我的问题.我会解释一下
我有一个包含250个项目(国家/地区)的列表,我想要存储数据.数据是未定义的长度,这意味着每个“列”可以保存多个条目,有时候没有条目,有时候是4等.
在PHP中我可以这样做:
$country_data = new array();
$country_data["nl"]["currency"] = "euro";
$country_data["nl"]["languages"] = "Dutch";
...
$country_data["us"]["currency"] = "US dollar";
$country_data["us"]["languages"] = array("English","Spanish");
所以有时候我想存储一个数组,有时不是.当然它也可以是只有一个条目而不是字符串的数组,但我只是说.
那么问题是,如何在HashMap中存储和获取数组中的数组?我明白我几乎陷入丑化的HashMap解决方案,但是我仍然看不到如何让我存储数组,我确定我忽略了一些简单的东西.基于我的一个例子将是伟大的!
UPDATE
我选择了HashMaps的HashMaps
这样做的原因我可以轻松地监督一切,并在需要时改变一些价值观.这是灵活的,我可以很容易地根据国家代码,一种语言获得一个国家名称,或者我可以得到country_data HashMap,当我需要它,或所有国家的名字等.
public class iso_countries {
Map country_data = new HashMap();
Map country_name = new HashMap();
Map country_idd = new HashMap();
Map country_cid = new HashMap();
public iso_countries(){
country_name.put("nl","Netherlands");
country_idd.put("nl",new String[]{"+31"});
country_cid.put("nl",new String[]{"#31#","*31#"});
setData(country_name,country_cid,country_idd);
// 249 * 4 lines more and later...
}//end method
public void setData(Map country_name,Map country_cid,Map country_idd){
country_data.put("name",country_name);
country_data.put("idd",country_idd);
country_data.put("cid",country_cid);
}//end method
public String getCountryName(String countryCode){
String name = country_name.get(countryCode);
return name;
}//end method
public String[] getCountryIdd(String countryCode){
String prefix[] = country_idd.get(countryCode);
return prefix;
}//end method
public String[] getCountryCid(String countryCode){
String cid[] = country_cid.get(countryCode);
return cid;
}//end method
}//end class