hashmap the method and put putIfAbsent method

When put into the data, if the key data into existing data that existed prior to the Map, and finally into a data overwrite,

When placed in the putIfAbsent data, if the duplicate key exists, it does not put putIfAbsent value.

putIfAbsent    If the incoming value corresponding to key already exists, the present value is returned, the replacement is not performed. If not, just add key and value, return 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);
});
}

}

 

result:

1:2
null
2

Guess you like

Origin www.cnblogs.com/dengw125792/p/12612040.html