【易懂】Java源码角度分析put()与putIfAbsent()的区别——源码分析系列
一、put()方法
1. 源碼分析
Java中并未給出put()的源碼,因此我們看一下put()方法中給出的注釋:
Associates the specified value with the specified key in this map (optional operation). If the map previously contained a mapping for the key, the old value is replaced by the specified value. (A map m is said to contain a mapping for a key k if and only if m.containsKey(k) would return true.)
翻譯過(guò)來(lái)就是:將key與value映射,如果在此之前存在以key為名稱的映射對(duì),則用新映射替換原來(lái)的舊映射。
2. 用法
Map<Integer, Integer>map = new HashMap<>(); // 定義一個(gè)map map.put(1,2); // 其中1是key,2是value二、putIfAbsent()
Map容器內(nèi)putIfAbsent()方法的源碼:
1. 源碼分析
default V putIfAbsent(K key, V value) {V v = get(key); // 首先調(diào)用get(key)方法,查看map中是否已經(jīng)存在key值相同的鍵值對(duì)if (v == null) { // 如果不存在,則調(diào)用put()方法插入鍵值對(duì)v = put(key, value);}return v; // 返回該鍵值對(duì)}也就是說(shuō),putIfAbsent()的作用是為map賦初值。
2. 用法
Map<Integer, Integer>map = new HashMap<>(); // 定義一個(gè)map map.putIfAbsent(1,0);// 查看key為1的值是否存在,如果不存在,將其value的值初始化為0擴(kuò)展用法:若映射不存在,則建立映射,并賦初值,若存在,則進(jìn)行其他操作
Map<Integer, Integer>map = new HashMap<>(); // 定義一個(gè)map if(map.putIfAbsent(1,0) == null) System.out.println("該映射不存在,建立映射并賦初值"); else {System.out.println("該映射存在,進(jìn)行其他操作"); }三、二者區(qū)別
put()方法的作用是為map賦值,當(dāng)存在相同的鍵值對(duì)時(shí),會(huì)用新值覆蓋舊值。
putIfAbsent()的作用是是為map賦初值,若存在相同的鍵值對(duì),則不會(huì)進(jìn)行操作。
總結(jié)
以上是生活随笔為你收集整理的【易懂】Java源码角度分析put()与putIfAbsent()的区别——源码分析系列的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 【击败时间100%】剑指 Offer 3
- 下一篇: 【图解】java8性能对比_Java 1