我遇到了很多人似乎面临来自PHP的相同问题,缺乏体面和易用的关联数组解决方案。 我读过这里的基本上所有建议使用HashMap,像这样问:Java associative-array关联数组和Java
但是,我不认为上述解决方案将解决我的问题。我会解释。
我有一个包含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这样 这样做的原因,我需要能够很容易地监督一切,并在需要时更改值的几行包含HashMap。这很灵活,我可以很容易地根据国家代码或语言获取国家/地区名称,或者我可以在需要时获得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
你想在HashMap像行为在PHP中,或者你会在Java中实现代码? –
为什么您的列表中有国家代码和索引? '$ country_data [“我们”]没有完美的工作吗? –
只是为了评论你的PHP代码:它甚至没有任何意义,在''语言''索引中的值类型可以完全不同,一旦一个字符串,一旦数组...你应该决定你喜欢,并坚持下去。混合类型表示一种非常糟糕的编码习惯,它会使你的代码不稳定。编辑:@Brendan龙:是的,这也是一个很好的通知。 – Sk8erPeter