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,也不会引起报错。

原文地址:https://www.cnblogs.com/clsriz/p/15011567.html