【易懂】Java源码角度分析put()与putIfAbsent()的区别——源码分析系列
生活随笔
收集整理的這篇文章主要介紹了
【易懂】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.)
翻譯過來就是:將key與value映射,如果在此之前存在以key為名稱的映射對,則用新映射替換原來的舊映射。
2. 用法
Map<Integer, Integer>map = new HashMap<>(); // 定義一個map map.put(1,2); // 其中1是key,2是value二、putIfAbsent()
Map容器內putIfAbsent()方法的源碼:
1. 源碼分析
default V putIfAbsent(K key, V value) {V v = get(key); // 首先調用get(key)方法,查看map中是否已經存在key值相同的鍵值對if (v == null) { // 如果不存在,則調用put()方法插入鍵值對v = put(key, value);}return v; // 返回該鍵值對}也就是說,putIfAbsent()的作用是為map賦初值。
2. 用法
Map<Integer, Integer>map = new HashMap<>(); // 定義一個map map.putIfAbsent(1,0);// 查看key為1的值是否存在,如果不存在,將其value的值初始化為0擴展用法:若映射不存在,則建立映射,并賦初值,若存在,則進行其他操作
Map<Integer, Integer>map = new HashMap<>(); // 定義一個map if(map.putIfAbsent(1,0) == null) System.out.println("該映射不存在,建立映射并賦初值"); else {System.out.println("該映射存在,進行其他操作"); }三、二者區別
put()方法的作用是為map賦值,當存在相同的鍵值對時,會用新值覆蓋舊值。
putIfAbsent()的作用是是為map賦初值,若存在相同的鍵值對,則不會進行操作。
總結
以上是生活随笔為你收集整理的【易懂】Java源码角度分析put()与putIfAbsent()的区别——源码分析系列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【击败时间100%】剑指 Offer 3
- 下一篇: 【图解】java8性能对比_Java 1