应该很简单,但它让我发疯!
有一个 HashMap,其 Key:Value 对分别为 Long:Dto。
当我调试时,我可以看到 Hashmap 中以 Long 值作为键的一个条目 - 但是当我尝试使用该键的 get() 时,我得到一个 null。
对于以下内容:
Map<Long, Dto> response = getMap();
System.out.println("Contents of HashMap: " + response);
System.out.println("Size of HashMap: " + response.size());
System.out.println("HashMap Keyset: " + response.keySet());
System.out.println("HashMap Contains: " + response.containsKey(19999984L));
System.out.println("HashMap Object: " + response.get(19999984L));
我得到以下输出:
Contents of HashMap: {19999984={productOptionId=19999984, amount={amount=20.99, currency=EUR}, pricingType=MSRP}}
Size of HashMap: 1
HashMap Keyset: [19999984]
HashMap Contains: false
HashMap Object: null
如果有任何建议,我们将不胜感激...这肯定有效!
也许我遗漏了一些明显的东西。
答案:看来我的键值是 String 类型 - 如下:
System.out.println("Contents of HashMap: " + response);
System.out.println("Size of HashMap: " + response.size());
System.out.println("HashMap Keyset: " + response.keySet());
System.out.println("HashMap Contains: " + response.containsKey("19999984"));
System.out.println("HashMap Object: " + response.get("19999984"));
System.out.println("HashMap Class: " + response.getClass());
最佳答案
您的 HashMap 中的键是 int 类型,并且您的 contains 方法具有 19999984L 这是 long 类型。
Contents of HashMap: {19999984={productOptionId=19999984, amount={amount=20.99, currency=EUR}, pricingType=MSRP}}
Size of HashMap: 1
System.out.println("HashMap Contains: " + response.containsKey(19999984L));
这就是错误的原因。
关于java - 使用键检索时,Hashmap 未按预期返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51107881/