HashMap中的putIfAbsent使用示例

原文:https://blog.csdn.net/k3108001263/article/details/83720445

 

  • 如果不存在key,则添加到HashMap中,跟put方法相似
  • 如果存在key,则不会覆盖,HashMap不受影响,而put方法会覆盖更新
import java.util.HashMap;
import java.util.Map;

public class Test {
    public static void main(String[] args) throws Exception {
        Map<String, String> map = new HashMap<>();
        map.put("message", "hello");
        map.putIfAbsent("message", "world");
        System.out.println(map);
    }
} 

打印结果是

{message=hello}

posted @ 2019-08-20 13:30  这个名字想了很久~  阅读(740)  评论(0编辑  收藏  举报