hashmap的put方法与putIfAbsent方法

put在放入数据时,如果放入数据的key已经存在与Map中,最后放入的数据会覆盖之前存在的数据,

而putIfAbsent在放入数据时,如果存在重复的key,那么putIfAbsent不会放入值。

putIfAbsent   如果传入key对应的value已经存在,就返回存在的value,不进行替换。如果不存在,就添加key和value,返回null

package t1;

import java.util.concurrent.ConcurrentHashMap;

public class TestThread24 {

public static void main(String[] args) {
ConcurrentHashMap<String, String> chm = new ConcurrentHashMap<>();//并发包中的ConcurrentHashMap,线程安全
String a = chm.putIfAbsent("1", "2");
String b = chm.putIfAbsent("1", "3");
chm.forEach((key, value) -> {
System.out.println(key + ":" + value);
System.out.println(a);
System.out.println(b);
});
}

}

结果:

1:2
null
2

猜你喜欢

转载自www.cnblogs.com/dengw125792/p/12612040.html
今日推荐