java - 当异常发生时如何运行迭代

标签 java dictionary data-structures hashmap

我有一个 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/

相关文章:

python - 检查列标题起始字符

java - 使用hibernate + jersey ws进行CRUD操作

java - 在这种情况下,将创建 UserHandler 类的多少个实例?

python - 三个列表压缩到字典列表中

flutter - Dart - 从 map 中的 map 读取键和值

algorithm - 仅使用一个堆栈实现优先级队列

c# - 有偏见的元素生成算法

python - 在 Python 中使用可选的 For 子句遵守 DRY 的最佳方式

java - Selenium Web 驱动程序 - 无法找到元素

java - 使用正则表达式进行流模式匹配