我遇到了许多人似乎都会面临的问题,即缺乏一个好用且易于使用的关联数组解决方案。我在这里看到了一些问题,基本上都建议使用HashMap,例如这个问题: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解决方案中,但我仍然看不到如何让我存储数组,我肯定是忽略了一些简单的东西。一个基于我的示例的示例将非常棒!
更新
我选择使用HashMaps of HashMaps。 原因是我需要能够轻松地监控所有内容,并在需要更改几行值时进行更改。而且这很灵活,我可以根据国家代码获取国家名称、语言,或者在需要时获取country_data HashMap,或者所有国家名称等。
public class iso_countries {
Map<String, Object> country_data = new HashMap<String, Object>();
Map<String, String> country_name = new HashMap<String, String>();
Map<String, String[]> country_idd = new HashMap<String, String[]>();
Map<String, String[]> country_cid = new HashMap<String, String[]>();
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
$country_data["us"]
不是完全可以正常工作吗? - Brendan Long'language'
索引中的值类型可以完全不同,有时是字符串,有时是数组...你应该决定你更喜欢哪种类型,并坚持使用它。混合类型表明了一种非常糟糕的编码实践,它会使你的代码变得不稳定。编辑:@Brendan Long:是的,这也是一个很好的注意点。 - Sk8erPeter