put與putIfAbsent區別

put與putIfAbsent區別,put在放入數據時,若是放入數據的key已經存在與Map中,最後放入的數據會覆蓋以前存在的數據,而putIfAbsent在放入數據時,若是存在重複的key,那麼putIfAbsent不會放入值。java

底層實現:code

public V put(K key, V value) { 
     if (value == null) 
          throw new NullPointerException(); 
     int hash = hash(key.hashCode()); 
     return segmentFor(hash).put(key, hash, value, false); 
} 
public V putIfAbsent(K key, V value) { 
     if (value == null) 
          throw new NullPointerException(); 
     int hash = hash(key.hashCode()); 
     return segmentFor(hash).put(key, hash, value, true); 
}

put事例:hash

Map<Integer, String> map = new HashMap<>();
map.put(1, "張三");
map.put(2, "李四");
map.put(1, "王五");
map.forEach((key,value)->{
    System.out.println("key = " + key + ", value = " + value);
});

輸出結果:io

key = 1, value = 王五
key = 2, value = 李四

putIfAbsent事例:class

Map<Integer, String> putIfAbsent = new HashMap<>();
putIfAbsent.putIfAbsent(1, "張三");
putIfAbsent.putIfAbsent(2, "李四");
putIfAbsent.putIfAbsent(1, "王五");
putIfAbsent.forEach((key,value)->{
	System.out.println("key = " + key + ", value = " + value);
});

輸出結果:map

key = 1, value = 張三
key = 2, value = 李四
相關文章
相關標籤/搜索