码迷,mamicode.com
首页 > 其他好文 > 详细

put与putIfAbsent区别

时间:2018-06-20 15:40:11      阅读:1903      评论:0      收藏:0      [点我收藏+]

标签:lis   col   system   区别   span   pack   import   val   util   

put与putIfAbsent区别,put在放入数据时,如果放入数据的key已经存在与Map中,最后放入的数据会覆盖之前存在的数据,而putIfAbsent在放入数据时,如果存在重复的key,那么putIfAbsent不会放入值。


底层实现:

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); 
}

例子:

package com.xx;

import java.util.HashMap;
import java.util.Map;

/**
 * JustForTest
 *
 * @create 2018-06-20 12:14
 */
public class TestHan {

    public static void main(String[] args) {

        /**
         * put
         */
        Map<Integer,String> map = new HashMap<>();
        map.put(1,"ZhangSan");
        map.put(2,"LiSi");
        map.put(1,"WangWu");
        map.forEach((key,value) ->{
            System.out.println("key : " + key + " , value : " + value);
        });

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

输出结果:

key : 1 , value : WangWu

key : 2 , value : LiSi

key : 1 , value : 张三

key : 2 , value : 李四



put与putIfAbsent区别

标签:lis   col   system   区别   span   pack   import   val   util   

原文地址:http://blog.51cto.com/hanchaohan/2130916

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!