关联数组和Java

我遇到同样的问题,很多人似乎面临来自 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<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的值:
HashMap<Integer,String[]> hm = new HashMap<Integer,String[]>();
hm.put( 1,new String[]{ "a","b" } );

至于具有“多维度”键,您可以随时将它们包装在一起.另一个,虽然丑陋的解决方案将是HashMaps的HashMaps.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...