首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HashMap of hashMap

HashMap of hashMap
EN

Stack Overflow用户
提问于 2015-09-20 14:45:17
回答 2查看 63关注 0票数 1

我有以下内容:

氢化物锂: Li 1H1#评论.

我希望得到以下结果:

{氢化锂:{‘Li’:1,‘H’:1},.}

我是这样做的:

代码语言:javascript
复制
public static HashMap<String,HashMap<String,Integer>> readFormulas(String content){
    HashMap<String,Integer> dictionnaire1 = new HashMap<String,Integer>();
        HashMap<String,HashMap<String,Integer>> dictionnaire2 = new HashMap<String,HashMap<String,Integer>>();
        ArrayList <String>  al = new ArrayList<String>();
        al.add(Arrays.toString(content.split(":")));// on met chaque ligne dans un tableau
        String str[] = content.split("\n");
        for(int i = 0 ; i < str.length;i++){//pour chaque ligne 
            String str2 [] = str[i].split(":");// séparer les noms des molécules des noms scientiques et des  commentaires ["Helium","he 1 #fzefzezfezfz"
            String NomMolecule = str2[0];
            String diese [] = str2[1].split("#");
            String description [] = diese[0].split(" ");
            int nb = Integer.parseInt(description[2]);
            dictionnaire1.put(description[1], nb);
            }
            dictionnaire2.put(NomMolecule,dictionnaire1);
        }
      return(dictionnaire2);
     }

但是结果很糟糕,我不明白为什么?:条目:

代码语言:javascript
复制
 HashMap<String,HashMap<String,Integer>> formulas = readFormulas("helium : he 3 #fsdfsfsdfsf" + "\n" + "lithium hydride : Li 1 H 1 #fdvdfdfvd");

结果:

{氢化锂={he=3,Li=1},氦={he=3,Li=1}

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2015-09-20 14:54:27

每个分子都需要一个HashMap:

代码语言:javascript
复制
for(int i = 0 ; i < str.length;i++){//pour chaque ligne 
    String str2 [] = str[i].split(":");
    String NomMolecule = str2[0];
    String diese [] = str2[1].split("#");
    String description [] = diese[0].trim().split(" ");
    HashMap<String,Integer> dictionnaire1 = new HashMap<>();
    for( int j = 0; j < description.length; j += 2 ){
        int nb = Integer.parseInt(description[j+1]);
        dictionnaire1.put(description[j], nb);
    }
    dictionnaire2.put(NomMolecule,dictionnaire1);
}

你也错过了一个环,在一个分子的成分(例如,Li _1H_ 1)上,这是我添加的。

票数 1
EN

Stack Overflow用户

发布于 2015-09-20 14:58:19

代码语言:javascript
复制
HashMap<String,Integer> dictionnaire1 = new HashMap<String,Integer>();

由于这个HashMap在每个循环迭代中都被重用,所以以前的(陈旧的)映射元素会产生错误的输出。

说明:

在第一次迭代中dictionnaire1:{he:3}

在第二次迭代中,相同的映射将与以前的字段数据一起重用。

找到的数据项- {Li: 1} & {he:3}

就是这样,你得到了结果。{Li: 1,he:3}

要获得所需的结果:

First您需要在每次迭代中清除dictionnaire1的所有先前条目。

第二个,您需要调整逻辑,从description数组中检索多个元素-

代码语言:javascript
复制
for(int j=1;j<description.length-1;j+=2){
    int nb = Integer.parseInt(description[j+1]);
    dictionnaire1.put(description[j], nb);
}
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32680630

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档