call to map.get inside For/in loop throws nullpointerexception while iterator doesn't

I broke my brain on it for a few hours, but need to carry on and found an ugly workaround, but I'd be happy to cleanup my code, here's the problem: public static void function1(Map map) { for(String key : map.keySet()) { Float val = map.get(key); // val is null here, throws NPE as soon as we try to use it } } public static void function2(Map map) { Iterator> it = map.entrySet().iterator(); while(it.hasNext()) { Entry entry = it.next(); String key = entry.getKey(); Float val = entry.getValue(); // do something with key & val, works fine } } the argument `Map map` of course is correctly initialized and doesn't contain any null value. on a side note, function1 works fine if I change the argument to Map map and use string pairs only. My goal is to to have only 1 function with generics `Map map` which I could use for both type of maps. any suggestion appreciated, thanks! thomas ---------- EDIT: I added some really basic introspection to make the function work with generics. I can confirm that I'm still getting null values when using the keyset, while I followed the suggestion below to use the entryset. here's my code below (the 1st function works fine, while the second returns null elements. // yeah, it's aweful, but it works. public static JsonNode map2JSON(Map map) { ObjectNode dummyObject = Json.newObject(); ArrayNode result = dummyObject.putArray("dummyKey"); for(Entry entry : map.entrySet()) { ObjectNode mapElementNode = result.addObject(); if("java.lang.String".equalsIgnoreCase(entry.getKey().getClass().getName())) { String key = (String)entry.getKey(); if("java.lang.Float".equalsIgnoreCase(entry.getValue().getClass().getName())) { Float val = (Float)entry.getValue(); mapElementNode.put(key, val); } else if("java.lang.String".equalsIgnoreCase(entry.getValue().getClass().getName())) { String val = (String)entry.getValue(); mapElementNode.put(key, val); } } } return result; } // result here contains valid keys (the string part) and null values (the float part) @Deprecated public static JsonNode mapSF2JSON(Map map) { ObjectNode dummyObject = Json.newObject(); ArrayNode result = dummyObject.putArray("dummyKey"); for(String key : map.keySet()) { ObjectNode mapElementNode = result.addObject(); mapElementNode.put(key, map.get(key)); } return result; }
How are Strings inserted while creating map? Could you post that snippet?

以上就是call to map.get inside For/in loop throws nullpointerexception while iterator doesn't的详细内容,更多请关注web前端其它相关文章!

赞(0) 打赏
未经允许不得转载:web前端首页 » JavaScript 答疑

评论 抢沙发

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址

前端开发相关广告投放 更专业 更精准

联系我们

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

微信扫一扫打赏