在Java中使用for循环创建映射时,Kep的值始终保持为0

时间:2019-01-30 09:51:34

标签: java data-structures hashmap

我正在尝试将Map<String, Object>放在Map<String, Map<String, Object>>上。

下面是代码:

Map<String, Object> createmap = new HashMap<String, Object>();
Map<String, Object> result = new HashMap<String, Object>();

for (int j=0 ; j<jsonarr2.size(); j++ )
{
    JSONObject jsonobj2 = (JSONObject) jsonarr2.get(j);
    Iterator<String> key2 = jsonobj2.keySet().iterator();
    while (key2.hasNext()) {
        String k2 = key2.next();
        createmap.put(k2, jsonobj2.get(k2));    
    }
    System.out.println("Print J:" + j + " CREATE MAP:" + createmap);
    result.put(Integer.toString(j),createmap);
    System.out.println("result :" + result);
}

For循环运行5次,createmap中将有5条记录。 但是,映射result始终将键用作0,因此createmap映射中仅result的最后一条记录可用。

循环内print语句的输出:

Print J:0 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0001","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0001","timestamp":1548643752}}}}}
Print J:1 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0002","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0002","timestamp":1548643752}}}}}
Print J:2 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0003","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0003","timestamp":1548643752}}}}}
Print J:3 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0004","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0004","timestamp":1548643752}}}}}
Print J:4 CREATE MAP:{vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0005","timestamp":1548643752}}}}
result : {0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0005","timestamp":1548643752}}}}}

但是最后一个Map只有

{0={vsan_name={"value":{"0":{"sequence":0,"value":"VSAN0005","timestamp":1548643752}}}}}

键始终保持为0,并且值将更新为同一键。

1 个答案:

答案 0 :(得分:2)

看起来jsonarr2.size()是1,因此循环只运行一次(即使嵌套的JSONObject有5个键。

此外,您可能会从json数组中的不同json对象中获取具有相同键的记录。尝试在createMap循环内移动for的实例化,例如:

Map<String, Object> result = new HashMap<String, Object>();

for (int j=0 ; j<jsonarr2.size(); j++ )
{
    Map<String, Object> createmap = new HashMap<String, Object>();
    JSONObject jsonobj2 = (JSONObject) jsonarr2.get(j);
    Iterator<String> key2 = jsonobj2.keySet().iterator();
    while (key2.hasNext()) {
        String k2 = key2.next();
        createmap.put(k2, jsonobj2.get(k2));    
    }
    System.out.println("Print J:" + j + " CREATE MAP:" + createmap);
    result.put(Integer.toString(j),createmap);
}