昨天写代码的时候需要往容器中添加null,所以主要测试了几个常见的容器能否添加null的情况,如下:
public class TestNull {
public static void main(String[] args) {
//HashMap 允许null-null键值对
Map<String,String> hashMap = new HashMap<String,String>();
try {
hashMap.put("test1", "value1");
hashMap.put("test2", null);
hashMap.put(null, "value2");
hashMap.put(null, null);
System.out.println("HashMap添加null-null成功。" + "(hashMap.size() = " + hashMap.size() + ")" );
} catch (Exception e) {
System.out.println("Hash添加失败。" + "(Error : " + e.toString() + ")");
}
//TreeMap 不允许(null,null),允许value为null 会调用比较器
TreeMap<String,String> treeMap1 = new TreeMap<String,String>();
try {
treeMap1.put("test1", null);
treeMap1.put("test2", null);
System.out.println("TreeMap添加value为null成功。");
} catch (NullPointerException e) {
System.out.println("TreeMap添加value为null失败。" + "(Error : " + e.toString() + ")");
}
TreeMap<String,String> treeMap2 = new TreeMap<String,String>();
try {
treeMap2.put(null, null);
System.out.println("TreeMap添加(null,null)成功");
} catch (NullPointerException e) {
System.out.println("TreeMap添加(null,null)失败。" + "(Error : " + e.toString() + ")");
}
//TreeSet 不允许 跟TreeMap都是用红黑树实现的 也会调用比较器
Set<String> treeSet = new TreeSet<String>();
try {
treeSet.add(null);
System.out.println("TreeSet添加null成功。");
}catch (NullPointerException e) {
System.out.println("TreeSet添加null失败。" + "(Error : " + e.toString() + ")");
}
//HashSet
Set<String> hashSet = new HashSet<String>();
try {
hashSet.add(null);
hashSet.add("test");
System.out.println( "HashSet添加null成功。" + "(hashSet.size() = " + hashSet.size() + ")" );
}catch (NullPointerException e) {
System.out.println("HashSet添加null失败。" + "(Error : " + e.toString() + ")");
}
//ArrayList
List<String> arrayList = new ArrayList<String>();
try {
arrayList.add(null);
arrayList.add("test");
System.out.println( "ArrayList添加null成功。" + "(arrayLisht.size() = " + arrayList.size() + ")" );
} catch (NullPointerException e) {
System.out.println("ArrayList添加null失败。" + "(Error : " + e.toString() + ")");
}
//LinkedList
List<String> linkedList = new LinkedList<String>();
try {
arrayList.add(null);
arrayList.add("test");
System.out.println( "LinkedList添加null成功。" + "(linkedList.size() = " + linkedList.size() + ")" );
} catch (NullPointerException e) {
System.out.println("LinkedList添加null失败。" + "(Error : " + e.toString() + ")");
}
Deque<String> arrayDeque = new ArrayDeque<String>();
try {
arrayDeque.addFirst(null);
System.out.println( "ArrayDeque添加null成功。" + "(arrayDeque.size() = " + arrayDeque.size() + ")" );
} catch (Exception e) {
System.out.println("ArrayDeque添加null失败。" + "(Error : " + e.toString() + ")");
}
}
}
测试结果如下:
HashMap添加null-null成功。(hashMap.size() = 3)
TreeMap添加value为null成功。
TreeMap添加(null,null)失败。(Error : java.lang.NullPointerException)
TreeSet添加null失败。(Error : java.lang.NullPointerException)
HashSet添加null成功。(hashSet.size() = 2)
ArrayList添加null成功。(arrayLisht.size() = 2)
LinkedList添加null成功。(linkedList.size() = 0)
ArrayDeque添加null失败。(Error : java.lang.NullPointerException)