嵌套的HashMap无法正常工作

时间:2014-04-02 13:03:14

标签: java collections map hashmap hashtable

我在HashMap中声明了HashMap但它为所有关键字取了重复值为什么我没有得到

当我在循环内部声明链接时,这个问题就解决了 我的代码......

public static void setM(){

    HashMap<String, HashMap<String, String>> response = new HashMap<String, HashMap<String,String>>();
    HashMap<String,String> link = new HashMap<String,String>();
    for(int i=0;i<6;i++){
        link.put("save_pont", "i"+i);
        response.put(i+"",link);// error here for putting same value for all key
        System.out.println("response ->   "+response);

    }

}

输出我正在......

response ->   {0={save_pont=i0}}
response ->   {1={save_pont=i1}, 0={save_pont=i1}}
response ->   {2={save_pont=i2}, 1={save_pont=i2}, 0={save_pont=i2}}
response ->   {3={save_pont=i3}, 2={save_pont=i3}, 1={save_pont=i3}, 0={save_pont=i3}}
response ->   {3={save_pont=i4}, 2={save_pont=i4}, 1={save_pont=i4}, 0={save_pont=i4}, 4={save_pont=i4}}
response ->   {3={save_pont=i5}, 2={save_pont=i5}, 1={save_pont=i5}, 0={save_pont=i5}, 5={save_pont=i5}, 4={save_pont=i5}}

但我需要输出像..

response ->   {0={save_pont=i0}}
response ->   {1={save_pont=i1}, 0={save_pont=i0}}
response ->   {2={save_pont=i2}, 1={save_pont=i1}, 0={save_pont=i0}}
response ->   {3={save_pont=i3}, 2={save_pont=i2}, 1={save_pont=i1}, 0={save_pont=i0}}
response ->   {3={save_pont=i3}, 2={save_pont=i2}, 1={save_pont=i1}, 0={save_pont=i0}, 4={save_pont=i4}}
response ->   {3={save_pont=i3}, 2={save_pont=i2}, 1={save_pont=i1}, 0={save_pont=i0}, 5={save_pont=i5}, 4={save_pont=i4}}

3 个答案:

答案 0 :(得分:0)

您正在使用“save_pont”键两次:

link.put("save_pont", "i"+i);

从而删除上一个条目。我想你想要的是将嵌套的HashMap构造放在循环中。

答案 1 :(得分:0)

由于您使用相同的hashmap并且只是覆盖了值。   在for循环内声明hashmap,如下所示

 public static void setM(){

        HashMap<String, HashMap<String, String>> response = new HashMap<String, HashMap<String,String>>();
        for(int i=0;i<6;i++){
            HashMap<String,String> link = new HashMap<String,String>();
             link.put("save_pont", "i"+i);
            response.put(i+"",link);
            System.out.println("response ->   "+response);

        }

    }

答案 2 :(得分:0)

link对象改变每次循环迭代。这可能会对你有所帮助:

public static void setM(){

    HashMap<String, HashMap<String, String>> response = new HashMap<String, HashMap<String,String>>();

    HashMap<String,String>[] links = new HashMap<String,String>[6];

    for(int i=0;i<6;i++){
        links[i] = new HashMap<String,String>();    
        links[i].put("save_pont", "i"+i);
    }

    for(int i=0;i<6;i++){
        HashMap<String,String> link = new HashMap<String,String>();
        response.put(i+"",links[i]);
        System.out.println("response ->   "+response);   
    }    
}