【发布时间】:2012-06-07 01:20:33
【问题描述】:
我遇到了很多人似乎在使用 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 解决方案所困扰,但我仍然看不到这将如何让我存储数组,我确信我忽略了一些简单的东西。一个基于我的例子会很棒!
更新
我选择了 HashMaps 的 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
【问题讨论】:
-
您希望在 php 中实现类似 hashmap 的行为,还是在 java 中实现代码?
-
为什么您的列表有国家代码和索引?
$country_data["us"]不是很好用吗? -
只是评论您的 PHP 代码:这甚至没有任何意义,
'language'索引中的值类型可以完全不同,一次是字符串,一次是数组......你应该决定你喜欢哪个,并坚持下去。混合类型表示一种非常糟糕的编码实践,它会使您的代码不稳定。编辑:@Brendan Long:是的,这也是一个很好的通知。 -
Java 与 PHP 不是同一种语言,您不应该使用相同的技术。在这里,具有强类型字段的“国家”对象的地图和列表将是更合适的解决方案。
-
@BrendanLong 是的,确实不需要数字索引。我目前正在阅读所有答案,仍在学习 Java,所以我什至很难掌握一些答案!谢谢大家,我将进一步调查并用已回答标记适当的 Q 并发布我的解决方案以供将来参考。
标签: java arrays multidimensional-array