我遇到了很多人似乎面臨來自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