我有一个 HashMap ,并且 HashMap 中的某些值为空。所以我只想打印 HashMap 中的键和值对。所以我正在尝试
HashMap<Integer, ArrayList<Long>> map=new HashMap<Integer,ArrayList<Long>>();
try{
for(int s=0;s<map.size();s++){
// checking for null
if(map.get(s).size()>0 || map.get(s)!=null){
System.out.println(s+" is the key and "+map.get(s).size() +" is the size of values for the key and "+map.get(s).toString()+ " are the values");
}
}
}
catch(Exception e){
}
但是当第一个元素的值不为空时运行,并且在这种情况下只要它为空就停止。感谢任何帮助。
最佳答案
您的检查 null
是错误的。当您在检查可能为空值之前访问 size() 时,它是否为空。
更改表达式map.get(s).size()>0 ||如果您只想打印值,则将 map.get(s)!=null
更改为 map.get(s) != null && map.get(s).size() > 0
大小 > 0 或仅使用 if (map.get(s) != null)
。
关于java - 当异常发生时如何运行迭代,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43447539/