zoukankan      html  css  js  c++  java
  • Salesforce: 关于Map和List的NullPointerException问题

    Map<String, String> testMap;

    System.debug(testMap.isEmpty());

    List<String> testList;

    System.debug(testMap.isEmpty());

    此时会报错System.NullPointerException: Attempt to de-reference a null object

    Map<String, String> testMap;

    System.debug(testMap == null);

    List<String> testList;

    System.debug(testMap == null);

    testMap = new Map<String, String>();

    System.debug(testMap.isEmpty());

    testList = new List<String>();

    System.debug(testList.isEmpty());

    以上这段代码所有的debug都将得到true

    testMap = new Map<String, String>();

    System.debug(testMap == null);

    testList = new List<String>();

    System.debug(testList == null);

    以上这段代码所有的debug都将得到false

    所以如果想要判断一个未实例化的Map或者List是否为空,可以使用testMap == null

    如果想要判断一个已经实例化的Map或者List是否有值,可以使用testMap.isEmpty()而不可以使用testMap == null

    Map<String, String> testMap = new Map<String, String>();
    List<String> testList = new List<String>();
    String test;
    System.debug(testMap.containsKey(test));
    System.debug(testList.contains(test));
    test = '';
    System.debug(testMap.containsKey(test));
    System.debug(testList.contains(test));

    以上所有debug都将得到false

    由此可见在判断Map或者List是否包含一个值时,就算这个值是null,也不会引起报错。

  • 相关阅读:
    ASP.NET实现文件下载的功能
    优先队列的使用
    关于CSS设置样式的一点建议
    ASP.NET后台弹出消息的方法
    创建漂亮的 CSS 按钮的 10 个代码片段(转载)
    2020高考游记
    最后的OI(HAOI2020游记)
    2020 2 2 20 20
    祭最后的亡魂
    一个感人至深的故事
  • 原文地址:https://www.cnblogs.com/clsriz/p/15011567.html
Copyright © 2011-2022 走看看