目录(结论):

  • HashMap key 和 value 都可以为 null
  • HashTable、ConcurrentHashMap 中的 key 和 value 均不能为 null,但 ConcurrentHashMap 是主动判空,而 HashTable 的 value 主动判空,key 则是 调用 key.hashCode() 抛出异常

[toc]

HashMap key 和 value 都可以为 null

验证:

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
Map<Integer, Integer> map = new HashMap<>();
map.put(null, 1);
map.put(1, null);
System.out.println(map.get(null)); // 输出 1
System.out.println(map.get(1)); // 输出 null
System.out.println(map.get(99)); // 不存在的 key,输出 null
System.out.println(map.getOrDefault(99, -1)); // 不存在的 key,输出自定义的默认值 -1
}

源码1(key 为 null 的情况):

1
2
3
4
5
6
7
8
public V put(K key, V value) {
return putVal(hash(key), key, value, false, true);
}

static final int hash(Object key) {
int h;
return (key == null) ? 0 : (h = key.hashCode()) ^ (h >>> 16);
}

可以看出,hash(key) 方法,当 key 为 null 时,Hash 值为 0。

源码2(value 为 null 的情况):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
final V putVal(int hash, K key, V value, boolean onlyIfAbsent,
boolean evict) {
Node<K,V>[] tab; Node<K,V> p; int n, i;
if ((tab = table) == null || (n = tab.length) == 0)
n = (tab = resize()).length;
if ((p = tab[i = (n - 1) & hash]) == null)
tab[i] = newNode(hash, key, value, null);
else {
Node<K,V> e; K k;
if (p.hash == hash &&
((k = p.key) == key || (key != null && key.equals(k))))
e = p;
else if (p instanceof TreeNode)
e = ((TreeNode<K,V>)p).putTreeVal(this, tab, hash, key, value);
else {
for (int binCount = 0; ; ++binCount) {
if ((e = p.next) == null) {
p.next = newNode(hash, key, value, null);
if (binCount >= TREEIFY_THRESHOLD - 1) // -1 for 1st
treeifyBin(tab, hash);
break;
}
if (e.hash == hash &&
((k = e.key) == key || (key != null && key.equals(k))))
break;
p = e;
}
}
if (e != null) { // existing mapping for key
V oldValue = e.value;
if (!onlyIfAbsent || oldValue == null)
e.value = value;
afterNodeAccess(e);
return oldValue;
}
}
++modCount;
if (++size > threshold)
resize();
afterNodeInsertion(evict);
return null;
}

经过前面的测试代码实验,value 可以为 null,但是当 map 中 key 不存在时,也会返回 null (见源码2 第 41 行)。所以无法判断到底是 key 为 null,还是不存在,因此 JDK8 新增了 getOrDefault() 方法。

1
2
3
4
5
6
7
// Overrides of JDK8 Map extension methods

@Override
public V getOrDefault(Object key, V defaultValue) {
Node<K,V> e;
return (e = getNode(hash(key), key)) == null ? defaultValue : e.value;
}

HashTable 中的 key 和 value 均不能为 null

验证:

1
2
3
4
5
6
7
public static void main(String[] args) {
Map<Integer,Integer> map = new Hashtable<>();
// map.put(null, 1);
map.put(1, null);
}
// Exception in thread "main" java.lang.NullPointerException
// at java.util.Hashtable.put(Hashtable.java:461)

源码3(HashTable 的 key 和 value 均不能为 null):

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
public synchronized V put(K key, V value) {
// Make sure the value is not null
if (value == null) {
throw new NullPointerException();
}

// Makes sure the key is not already in the hashtable.
Entry<?,?> tab[] = table;
int hash = key.hashCode();
int index = (hash & 0x7FFFFFFF) % tab.length;
@SuppressWarnings("unchecked")
Entry<K,V> entry = (Entry<K,V>)tab[index];
for(; entry != null ; entry = entry.next) {
if ((entry.hash == hash) && entry.key.equals(key)) {
V old = entry.value;
entry.value = value;
return old;
}
}

addEntry(hash, key, value, index);
return null;
}

可以看到,第 4 行先检查了 value,为 null 直接抛出异常,然后第 9 行通过 key.hashCode() 获取 hash 值,所以 key 也不能为 null。

ConcurrentHashMap 中的 key 和 value 均不能为 null

验证:

1
2
3
4
5
6
7
8
9
public static void main(String[] args) {
Map<Integer,Integer> map = new ConcurrentHashMap<>();
// map.put(null, 1);
map.put(1, null);

// Exception in thread "main" java.lang.NullPointerException
// at java.util.concurrent.ConcurrentHashMap.putVal(ConcurrentHashMap.java:1011)
// at java.util.concurrent.ConcurrentHashMap.put(ConcurrentHashMap.java:1006)
}

源码:

1
2
3
4
5
6
7
8
9
public V put(K key, V value) {
return putVal(key, value, false);
}

/** Implementation for put and putIfAbsent */
final V putVal(K key, V value, boolean onlyIfAbsent) {
if (key == null || value == null) throw new NullPointerException();
// ...
}

ConcurrentHashMap 直接先对 key 和 value 进行了判空。