是在学习中遇到的问题,在此记录一下
情况1
package action;
import java.util.HashMap;
public class Test08 {
public static void main(String[] args) {
HashMap<String,String> hashMap = new HashMap<String,String>();
HashMap<String,String> map = new HashMap<String,String>();
map.put("TimeToLive", "10");
map.put("RequestID", "20000307439");
map.put("LogicalID",null);
map.put("ExpectedResponseTime", "2");
hashMap.putAll(map);
}
}
情况1,这种情况是可以正常运行的
情况2
package action;
import java.util.HashMap;
import java.util.Properties;
public class Test08 {
public static void main(String[] args) {
Properties properties = new Properties();
HashMap<String,String> map = new HashMap<String,String>();
map.put("Time", "10");
map.put("ID", "20000307439");
map.put("LogicalID",null);
map.put("ResponseTime", "2");
properties.putAll(map);
}
}
情况2运行的时候会抛出异常
Exception in thread "main" java.lang.NullPointerException
at java.util.Hashtable.put(Hashtable.java:514)
at java.util.Hashtable.putAll(Hashtable.java:587)
at action.Test08.main(Test08.java:14)
情况1和情况2的LogiclID的值都为null,当Properties类使用putAll()方法是会抛出异常,查看源码可以发现:
public class Properties extends Hashtable<Object,Object>
Properties类实现的Hashtable,我们都知道Hashtable是不支持key和value为null的。