java.util.Map中put,computeIfAbsent与putIfAbsent区别
computeIfAbsent和putIfAbsent區別是三點:
1、當Key存在的時候,如果Value獲取比較昂貴的話,putIfAbsent就白白浪費時間在獲取這個昂貴的Value上(這個點特別注意)
2、Key不存在的時候,putIfAbsent返回null,小心空指針,而computeIfAbsent返回計算后的值
3、當Key不存在的時候,putIfAbsent允許put null進去,而computeIfAbsent不能,之后進行containsKey查詢是有區別的(當然了,此條針對HashMap,ConcurrentHashMap不允許put null value進去)
4、computeIfAbsent的value是接受一個Function,而putIfAbsent是是接受一個具體的value,所以computeIfAbsent的使用應該是非常靈活的
下面代碼演示:
public V putIfAbsent(K key, V value)
? ? ? ?ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();System.out.println("put:" + map.putIfAbsent("hello", "123"));System.out.println(map.get("hello"));System.out.println("put:" + map.putIfAbsent("hello", "456"));System.out.println(map.get("hello"));輸入如下:
put:null 123 put:123 123putIfAbsent會返回之前的值,如果之前不存在,則返回null;而且put一個存在的key時,并不會覆蓋掉之前的key。
public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction)
? ? ? ?ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();System.out.println("put:" + map.computeIfAbsent("world", s -> "java"));System.out.println(map.get("world"));System.out.println("put:" + map.computeIfAbsent("world", s -> "php"));System.out.println(map.get("world"));輸出如下:
put:java java put:java javacomputeIfAbsent會返回本次計算的值,同時如果put的也是一個存在的key時,也不會覆蓋掉之前的key。
public V put(K key, V value)
? ? ? ?ConcurrentHashMap<String, Object> map = new ConcurrentHashMap<>();System.out.println("put:" + map.put("test", "python"));System.out.println(map.get("test"));System.out.println("put:" + map.put("test", "javascript"));System.out.println(map.get("test"));輸出如下:
put:null python put:python javascriptput會返回之前的值,如果之前不存在,則返回null。每次put的時候,都會更新對應的key值。
總結:
| put | 是 | 覆蓋前 |
| putIfAbsent | 否 | 覆蓋前 |
| computeIfAbsent | 否 | 覆蓋后 |
總結
以上是生活随笔為你收集整理的java.util.Map中put,computeIfAbsent与putIfAbsent区别的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 数据结构之数组、链表、栈和队列
- 下一篇: ThreadLocal线程复用导致的安全