Can the key value in HashMap HashTable ConcurrentMap be null?
Let’s talk about the conclusion first
Both the key and value of hashmap can be null; when the key is repeated, the value of the second key will overwrite the value of the first key.
HashTable's key and value cannot be null
ConcurrentMap stores data, and its key and value cannot be null.
1.HashMap
//key为null value为null
HashMap<String,String> hashMap=new HashMap<>();
hashMap.put(null,null);
hashMap.put("zhangsan",null);
System.out.println(hashMap);
//多个key为null
HashMap<String,String> hashMap2=new HashMap<>();
hashMap2.put(null,"111");
hashMap2.put(null,null);
System.out.println(hashMap2);
Conclusion: Both the key and value of a hashmap can be null; when the key is repeated, the value of the second key will overwrite the value of the first key.
principle
put method
get method
What is returned is null. At this time, it is not known whether the null value is not found or the corresponding value.
This raises a problem: when thread A uses containsKey() to make a judgment, it finds that there is this element. When it calls get() to get this element, thread B joins in, and thread B removes the element. At this time, the value obtained by thread A is null. Thread A will think that it has obtained this value, but in fact the null at this time is null that has not been found. In this way, security issues may arise between threads.
So much so that we use currentHashMap to store data in a multi-threaded situation, and its key and value cannot be null.
2.HashTable
//key为null
Hashtable<String, String> table = new Hashtable<String, String>();
table.put(null,"111");
System.out.println(table);
//value为null
Hashtable<String, String> table2 = new Hashtable<String, String>();
table2.put("zhangsan",null);
System.out.println(table2);
key is null
value is null
Conclusion None of the hashtable key values can be null
principle
3.ConcurrentMap
ConcurrentMap<String, String> concurrentMap = new ConcurrentHashMap<>();
//key为null
concurrentMap.put(null,"111");
System.out.println(concurrentMap);
ConcurrentMap<String, String> concurrentMap2 = new ConcurrentHashMap<>();
//key为null
concurrentMap2.put("zhangsan",null);
System.out.println(concurrentMap2);
key is null
value is null
principle