首页 > 解决方案 > 我收到一个字符串数组,并希望根据数组中收到的字符串访问哈希图

问题描述

 given String arr[] = {"hashmap1", "hashmap2"};
 Hashmap<String,Integer> hashmap1;
 Hashmap<String,Integer> hashmap2;

我怎样才能做到这一点:

for(int i=0;i<arr.length;i++){
   System.out.println(arr[i].get("value")); 

 // basically, arr[i] is the hashmap name and I want to access it
 }

我试图把所有hashmaps的东西都放进arraylist去,但那也没有用。

for(int i=0;i<cardNames.length;i++){

            boolean tmp = cardNames[i].containsKey(storeType);

我收到此错误:

错误:找不到符号 boolean tmp = cardNames[i].get(storeType); ^ 符号:方法 get(String) 位置:类 String

标签: javahashmap

解决方案


我相信您可以做的就是为您拥有的所有地图创建一个地图,并以名称为键。

像这样的东西:

 Map<String, Map<String,Integer>> superHashMap = new HashMap<>();
 String arr[] = {"hashmap1", "hashmap2"};
 Hashmap<String,Integer> hashmap1;
 Hashmap<String,Integer> hashmap2;

 superHashMap.put("hashmap1", hashmap1);
 superHashMap.put("hashmap2", hashmap2);

 How can I do this:
 for(int i=0;i<arr.length;i++){
   // This shall contain the desired hashMap that you would need for further processing.
   Map<String, Integer> mapYouNeedToAccess = superHashMap.get(arr[i]);
 }

推荐阅读