不能set一个null的key 或者value可是map是一个接口我一时还不知道怎么初始化了..... Map _map = Collections.EMPTY_MAP;
_map.put("a", "a");
System.out.println(_map.get("a"));
我这样一来得到 一个空指针!
我想知道怎么能测试map不能put一个null的key 或者value呢
_map.put("a", "a");
System.out.println(_map.get("a"));
我这样一来得到 一个空指针!
我想知道怎么能测试map不能put一个null的key 或者value呢
代码如下:
package main;
import java.util.HashMap;
import java.util.Map;public class Main {
public static void main(String[] args) {
try{
Map map = new HashMap();
map.put(null, "a");
map.put("a", null);
System.out.println((String)map.get(null));
System.out.println((String)map.get("a"));
}catch(Exception e){
e.printStackTrace(System.out);
}
}
}
结果如下:
a
null
那个Map是Interface不能实例化的。
*******************************
java.util
Interface MapAll Known Subinterfaces:
SortedMapAll Known Implementing Classes:
AbstractMap, Attributes, HashMap, Hashtable, IdentityHashMap, RenderingHints, TreeMap, WeakHashMap
*****************************************
以上是javadoc里面的,如果你硬是认为HashMap不是Map,那么你说说,“你的Map”是哪个Map?????