遍历HashMap时,我得到NullPointerException

这是我的代码:

HashMap<String, HashSet> map; ....// I didn't write those code that initial the map. System.out.println(map.entrySet().size()); // run util here is ok, I get the size of the map. for(Map.Entry<String, HashSet> entry : map.entrySet()) {// here throw the exception Sytem.out.println("abc");// didn't executed, throw exception before } 

我得到了例外:

key.test.EnwikiOutlink.main(EnwikiOutlink.java:68)中线程“main”java.lang.NullPointerException中的exception

map对象有超过10,000个map对象,我在服务器机器上运行它无法调试。 但是当我减小这个地图的大小(低于10,000)时,程序运行正常。 问题的原因和解决方案是什么? 谢谢!

map初始化在哪里? 如果你实际上没有为它分配任何东西,当然它将是null

(目前尚不清楚它是类成员还是局部变量。)

如果映射确实包含元素,则map.entrySet()不会抛出NullPointerException (因为映射不为null),因此exception必须来自访问循环中的一个元素(或其子对象)。

我刚试过这个:它工作得很好。 您的地图必须在某处指定为null。

 HashMap> map; map = new HashMap>(); for(Map.Entry> entry : map.entrySet()) { } 

如果map是局部变量(而不是实例字段), 理论上不可能map.entrySet().size()之后在map.entrySet().size()上获得NPE,即使地图本身可以被另一个访问线程和那个线程以各种可想象的方式改变了它。 如果stacktrace中的第一个条目是代码的一行,而不是从您的代码中调用的某些代码,那么发生这种情况的唯一方法是将map变量本身设为null 。 因此,我认为您需要重新审视您的诊断线索。